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!
CodePudding user response:
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; }
CodePudding user response:
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);