NodeJS JSON结构

时间:2019-02-10 18:24:45

标签: javascript arrays node.js json object

我目前有一个像这样的json数组:

[{"id": 1, "meeting": "1/3/2015 12:30:00 PM", "name": "John"},
{"id": 1, "meeting": "1/3/2015 13:30:00 PM"}, "name": "John"},
{"id": 2, "meeting": "1/5/2015 7:00:00 AM"}, "name": "Peter"},
{"id": 2, "meeting": "1/5/2015 8:00:00 AM"}, "name": "Peter"}]

如何更改数组的结构以使其看起来像这样?

[ {"id": 1, "name": "John", "meeting": [{"Time": "1/3/2015 12:30:00 PM", "Time": "1/3/2015 13:30:00 PM"}]},
{"id": 2, "name": "Peter", "meeting": [{"Time": "1/5/2015 7:00:00 AM", "Time": "1/5/2015 8:00:00 AM"}]}]

1 个答案:

答案 0 :(得分:1)

您应该使用Array.prototype.reduce

const data = [{"id": 1, "meeting": "1/3/2015 12:30:00 PM", "name": "John"}, {"id": 1, "meeting": "1/3/2015 13:30:00 PM", "name": "John"}, {"id": 2, "meeting": "1/5/2015 7:00:00 AM", "name": "Peter"}, {"id": 2, "meeting": "1/5/2015 8:00:00 AM", "name": "Peter"}];

//I fixed a typo in the above array

const merged = data.reduce((acc, { id, meeting, name }) => {
    if (acc.some(e => e.id == id)) {
        acc.find(e => e.id == id).meeting.push(meeting);
    } else {
        acc.push({ "id": id, "name": name, "meeting": [meeting]});
    }
    return acc;
}, []);

console.log(merged);