0

I have two object arrays:

 let arr1 = [{id: 100, quantity: 2, grp: 1A},{...},{...}, ...],

 let arr2 = [{id: 100, color: "#000"},{...},{...}, ...],    

arr2 contains objects with the id and color for every object from arr1.

My question is: How can I loop through both object arrays and add the color property of arr2 to the according object in arr1?

  • Possible duplicate of [JavaScript merging objects by id](https://stackoverflow.com/questions/19480008/javascript-merging-objects-by-id) – Neil Apr 08 '19 at 19:06

4 Answers4

1

Use forEach to loop over arr1, and inside that function, use filter to find the item of arr2 that is a match for the current item in arr1:

arr1.forEach(item=>item.color = arr2.filter(colorObj=>colorObj.id===item.id)[0].color)

Or, slightly more readably:

arr1.forEach(item=>{
    var matchingColorObj = arr2.filter(colorObj=>colorObj.id===item.id)[0];
    item.color = matchingColorObj.color;
});
apsillers
  • 112,806
  • 17
  • 235
  • 239
1

If you don't want to search through arr1 for every item of arr2 (making an O(n²) solution), you could make a lookup object for arr1 keyed to id. Then you can simply loop through arr2 merging the object found by looking it up. This will be more efficient if you have larger arrays.

let arr1 = [{id: 100, quantity: 2, grp: '1A'},{id: 101, quantity: 2, grp: '2A'}]
let arr2 = [{id: 101, color: "#FFF"}, {id: 100, color: "#000"}] 

// make lookup
let lookup = arr1.reduce((lookup, item) => lookup.set(item.id, item), new Map)

// assign color to correct object
arr2.forEach(({id, ...rest}) => Object.assign(lookup.get(id), rest))
console.log(arr1)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Maybe you can do something like this

    let arr1 = [{
      id: 100,
      quantity: 2,
      grp: 1 A
    }];

    let arr2 = [{
      id: 100,
      color: "#000"
    }];

    arr2.forEach(obj => {

      arr1.find(arr1_element => arr1_element.id == obj.id).color = obj.color;
    });

    console.log(arr1, arr2);
Adam Rich
  • 86
  • 2
  • 10
0
let arr1 = [{id: 100, quantity: 2, grp: 1A},{...},{...}, ...],

let arr2 = [{id: 100, color: "#000"},{...},{...}, ...],   

First creating lookup map from arr2 and then using .map() on the arr1 to assign values from the lookup table.

let lookupMap = new Map();
arr2.forEach((val,key)=>{
  lookupMap.set(val.id, val.color);
});

let mappedArray = arr1.map((obj)=> {
  let color = lookupMap.get(obj.id);
  return {...obj, color }
});

// mapped Array would be as 
//[ { id: 100, quantity: 2, grp: '1A', color: '#000' },
// {...},{...} ]