Как отобразить и сгруппировать массив объектов - PullRequest
1 голос
/ 12 апреля 2019

Я создаю приложение с Node.js, Express, Postgres и Sequelize.

Я получаю ответ, который выглядит следующим образом:

[
    {
        "id": 101,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 102,
        "type": 4,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 103,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 104,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    }
]

Я хочу сгруппировать все события, которые происходят в одну и ту же дату.

Я пытался

_.forEach(response, function(value) {
    _.groupBy(value, value.bookings[0].date)
})

но это не работает.

Как мне сопоставить и сгруппировать массив?

В конце концов я хочу получить объект (или массив), который будет выглядеть примерно так:

{
    2019-04-15: [
        { id: 101, type: 0 }, { id: 103, type: 0}
    ],
    2019-04-17: [
        { id: 102, type: 4 }, { id: 104, type: 0}
    ]
}

Ответы [ 5 ]

3 голосов
/ 12 апреля 2019

Вы можете использовать уменьшить

let data = [{"id": 101,"type": 0,"bookings": [{"date": "2019-04-15T02:00:00.000Z"}]},{"id": 102,"type": 4,"bookings": [{"date": "2019-04-17T02:00:00.000Z"}]},{"id": 103,"type": 0,"bookings": [{"date": "2019-04-15T02:00:00.000Z"}]},{"id": 104,"type": 0,"bookings": [{"date": "2019-04-17T02:00:00.000Z"}]}]

let op = data.reduce((op,{bookings,...rest}) => {
  let key = bookings[0].date.split('T',1)[0]
  op[key] = op[key] || []
  op[key].push(rest)
  return op
},{})

console.log(op)
0 голосов
/ 12 апреля 2019

Ну, я не видел так много ответов, но так как я сделал это тоже


const data = [
    {
        "id": 101,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 102,
        "type": 4,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 103,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 104,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    }
];

const bookingsByDate = {};

data.forEach((booking) => {    

    booking.bookings.forEach((bookingDate) => {
        const date = new Date(bookingDate.date);
        const day = date.getDate() < 10 ?  '0' + date.getDate(): date.getDate();
        const month = date.getMonth() < 10 ? '0' + date.getMonth(): date.getMonth();
        const year = date.getFullYear();

        const fullDate = year + '-' + month + '-' + day;

        if(!bookingsByDate[fullDate]) {
            bookingsByDate[fullDate] = [];
        }
        bookingsByDate[fullDate] = [
            ...bookingsByDate[fullDate],
            { 
                id: booking.id,
                type: booking.type,
            }
        ]
    });

})
console.log(bookingsByDate);
0 голосов
/ 12 апреля 2019

Вы также можете использовать это, чтобы выполнить то, что вы ищете.

let response = [
    {
        "id": 101,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 102,
        "type": 4,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 103,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-15T02:00:00.000Z"
            }
        ]
    },
    {
        "id": 104,
        "type": 0,
        "bookings": [
            {
                "date": "2019-04-17T02:00:00.000Z"
            }
        ]
    }
]

let dateGroupings = {};

response.forEach((v)=> {
  let date = v.bookings[0].date.substring(0,10)
  if (!dateGroupings[date]){
    dateGroupings[date] = [];
  }

  let obj = { 
    id: v.id,
    type: v.type
  };

  dateGroupings[date].push(obj); 

})
0 голосов
/ 12 апреля 2019

Попробуйте это:

const arr = [{
    "id": 101,
    "type": 0,
    "bookings": [{
        "date": "2019-04-15T02:00:00.000Z"
    }]
}, {
    "id": 102,
    "type": 4,
    "bookings": [{
        "date": "2019-04-17T02:00:00.000Z"
    }]
}, {
    "id": 103,
    "type": 0,
    "bookings": [{
        "date": "2019-04-15T02:00:00.000Z"
    },{
        "date": "2019-04-16T02:00:00.000Z"
    }]
}, {
    "id": 104,
    "type": 0,
    "bookings": [{
        "date": "2019-04-17T02:00:00.000Z"
    }]
}]

const yourObj = {};
arr.forEach(elem => {
    const bookings = elem.bookings;
    if (Array.isArray(elem.bookings)) {
        elem.bookings.forEach(obj => {
            const key = obj.date.split('T')[0];
//             var date = new Date(obj.date);
//             var key = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
               const {bookings, ...otherProp} = elem;
               yourObj[key] = yourObj[key] || [];
               yourObj[key].push(otherProp)
        })
    }
})

console.log(yourObj)
0 голосов
/ 12 апреля 2019

Вы можете использовать функцию reduce для группировки объектов по дате.

Предполагается, что массив имеет только один индекс.

let arr = [    {        "id": 101,        "type": 0,        "bookings": [            {                "date": "2019-04-15T02:00:00.000Z"            }        ]    },    {        "id": 102,        "type": 4,        "bookings": [            {                "date": "2019-04-17T02:00:00.000Z"            }        ]    },    {        "id": 103,        "type": 0,        "bookings": [            {                "date": "2019-04-15T02:00:00.000Z"            }        ]    },    {        "id": 104,        "type": 0,        "bookings": [            {                "date": "2019-04-17T02:00:00.000Z"            }        ]    }];

let result = arr.reduce((a, {id, type, bookings: [{date}]}) => {
  let key = date.substring(0, 10);
  (a[key] || (a[key] = [])).push({id, type});
  return a;
}, Object.create(null));


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
...