Home > Net >  Merge two array of objects with nested id
Merge two array of objects with nested id

Time:09-25

I have two arrays of objects that I need to combine where the nested ID (connect.id) of the second array matches the id of the first but can't see how to do it

can anyone help?

const arr1 = [
  { "id": 7619209572755, "title": "Title 1" },
  { "id": 7619209157372, "title": "Title 2" },
  { "id": 7619209921625, "title": "Title 3" }
];  
const arr2 = [
  {
    "id": 7619217289192,
    "connect": [
      { "id": 7619209157372, "title": "Title 1" }
    ],
    "value": "1"
  },
  {
    "id": 7619217242206,
    "connect": [
      { "id": 7619209921625, "title": "Title 2" }
    ],
    "value": "2"
  }
];
const expectedResult = [
  { "id": 7619209572755, "title": "Title 1" },
  { "id": 7619209157372, "title": "Title 2", "value": "1" },
  { "id": 7619209921625, "title": "Title 3", "value": "2" }
]

CodePudding user response:

  1. Using Array#reduce, iterate over arr2 to map every connect element's id with the its object's value in a Map
  2. Using Array#map, iterate over arr1, if an element's id is in the map, set its value

const 
  arr1 = [ { "id": 7619209572755, "title": "Title 1" }, { "id": 7619209157372, "title": "Title 2" }, { "id": 7619209921625, "title": "Title 3" } ],
  arr2 = [
    {
      "id": 7619217289192,
      "connect": [ { "id": 7619209157372, "title": "Title 1" } ],
      "value": "1",
    },
    {
      "id": 7619217242206,
      "connect": [ { "id": 7619209921625, "title": "Title 2" } ],
      "value": "2",
    }
  ];
  
const connectValueMap = arr2.reduce((map, { connect = [], value}) => {
  connect.forEach(({ id }) => map.set(id, value));
  return map;
}, new Map);

const merged = arr1.map(e => {
  const value = connectValueMap.get(e.id);
  if(value) e.value = value;
  return e;
});

console.log(merged);

  • Related