Tyler Liu Tyler Liu - 1 month ago 8
Javascript Question

how to traverse and compare object inside an array elements in javascript

given the following array structure:

[{ _id: '1234', characteristics: [[Object], [Object]]},
{ _id: '1234',characteristics: [[Object], [Object]]},
{ _id: '4567', characteristics: [[Object], [Object]]},
{ _id: '4567',characteristics: [ [Object], [Object]]},
{ _id: '4987',characteristics: [ [Object], [Object]]}]


how can I compare one array element with the next, and merge the object with the same id?

the end result is something like

[ { _id: '1234', characteristics: [ [Object], [Object] ,[Object], [Object] ]},
{ _id: '4567',characteristics: [ [Object], [Object] , [Object], [Object]]},
{ _id: '4987', characteristics: [ [Object], [Object] ] } ]


basically the objects inside both of the object with id of 1234 are merged together under characteristics.

I been staring at this for the past 2 hours, anyone have any idea? I'd prefer a more functional approach.

Answer

You can use reduce() with one helper object. You can also use concat() instead of ... and push() like this

var data = [{ _id: '1234', characteristics: [[1], [2]]},
{ _id: '1234',characteristics: [[3], [4]]},
{ _id: '4567', characteristics: [[5], [6]]},
{ _id: '4567',characteristics: [ [7], [8]]},
{ _id: '4987',characteristics: [ [9], [10]]}];

var o = {}
var result = data.reduce(function(r, e) {
  if (!o[e._id]) {
    o[e._id] = e;
    r.push(o[e._id]);
  } else {
    o[e._id].characteristics.push(...e.characteristics);
  }
  return r;
}, [])

console.log(result)