Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Merge two array of objects with nested id

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" }
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!