MANGESH KHAKE
MANGESH KHAKE

Reputation: 33

JSON Array union

I have 2 JSON Array as below Array 1:

[
    { id : 1, b: 1},
    { id : 2, b: 2},
    { id : 3, b: 3},
]

Array 2:

[
    { id : 1, c: 1},
    { id : 3, c: 3},
    { id : 4, c: 4}
]

And using nodejs code i need to union of both as below.

Union:

[
    { id : 1, b: 1, c:1},
    { id : 2, b: 2},
    { id : 3, b: 3, c:3},
    { id : 4, c: 4}
]

Could someone help the best possible way?

Upvotes: 0

Views: 1113

Answers (1)

Akrion
Akrion

Reputation: 18525

You can simply join the two arrays and then use Array.reduce to group the elements:

let a1 = [ { id : 1, b: 1}, { id : 2, b: 2}, { id : 3, b: 3} ]
let a2 = [ { id : 1, c: 1}, { id : 3, c: 3}, { id : 4, c: 4} ]

let result = [...a1, ...a2].reduce((acc,cur) => {
  acc[cur.id] = {...acc[cur.id] || {}, ...cur}
  return acc
}, {})

console.log(Object.values(result))

Upvotes: 2

Related Questions