-3

I have the following values -

const r = [{ id: 2, car: 'toyota}, {id: 1, car:'honda'}]

const s = [{ id: 2, name: 'Samuel'},{id: 1, name: 'James'}]

I want to match the arrays based on id and add name to each corresponding matched object id.

const res = [{id: , car: , name: }]

I have certain values I need to map together to make into one response object, so it needs to be an array of objects with various properties. I want to map based on an id and then loop through each object in the array and add the corresponding object. Kindly help, much appreciated!

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Kashyap
  • 85
  • 2
  • 9
  • 1
    Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+merge+object+arrays+group+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Dec 16 '21 at 09:42

2 Answers2

-1

You can easily achieve the result using Map and map

const r = [
  { id: 2, car: "toyota" },
  { id: 1, car: "honda" },
];

const s = [
  { id: 2, name: "Samuel" },
  { id: 1, name: "James" },
];

const map = new Map(r.map((o) => [o.id, o]));
const result = s.map((o) => ({ ...o, ...(map.get(o.id) ?? []) }));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
DecPK
  • 24,537
  • 6
  • 26
  • 42
-1

In this problem we need to filter the data & also need to map the data so for this direct filter operator won't work so I just solved your problem with a forEach loop.

const arr1 = [{ id: 2, car: 'toyota'}, {id: 1, car:'honda'}]

const arr2 = [{ id: 3, name: 'Samuel'},{id: 1, name: 'James'}]

const result = [];
arr1.forEach(arr1Obj=>{
  const matchedObject = arr2.find(arr2Obj=>arr2Obj.id==arr1Obj.id);
  if(matchedObject){
  result.push({...arr1Obj,...matchedObject});
  }
  
})
console.log(result);
abhishek sahu
  • 648
  • 4
  • 8