如何将具有匹配ID的数组中的对象连接在一起?

时间:2018-11-20 12:06:23

标签: javascript node.js

我收到的对象数组说明哪些事件已更改。以下代码是此类更改的示例。其他字段也可能会更改,但它们不会在此处显示。

[{ "eventId": "1", "name": "name_a", "isCancelled": "true"},
{ "eventId": "1", "name": "name_a", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true"},
{ "eventId": "3", "name": "name_c", "status": "Private"}]

是否可以将具有相同ID的对象组合在一起?与此类似。

[{ "eventId": "1", "name": "name_a", "isCancelled": "true", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true", "status": "Private"}

我见过很多线程,它们主要致力于通过匹配ID来组合2个数组。

1 个答案:

答案 0 :(得分:2)

您可以像下面那样使用for .. of遍历每个元素,然后根据event id并置对象

let arr = [{ "eventId": "1", "name": "name_a", "isCancelled": "true"},
{ "eventId": "1", "name": "name_a", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true"},
{ "eventId": "3", "name": "name_c", "status": "Private"}]

let o = {}
for(let d of arr) {
  o[d['eventId']] = { ...(o[d['eventId']] || {}), ...d }
}

console.log(Object.values(o))