比较两个对象数组并赋值

时间:2019-04-08 19:03:26

标签: javascript object ecmascript-6 functional-programming

我有两个对象数组:

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

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

arr2包含arr1中每个对象的ID和颜色为对象的对象。

我的问题是:如何遍历两个对象数组并将arr2的color属性添加到arr1中的相应对象?

4 个答案:

答案 0 :(得分:1)

使用forEach遍历arr1,并在该函数内部,使用filterarr2中查找与当前项目匹配的项目arr1 1}}:

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

或者,更具可读性:

arr1.forEach(item=>{
    var matchingColorObj = arr2.filter(colorObj=>colorObj.id===item.id)[0];
    item.color = matchingColorObj.color;
});

答案 1 :(得分:1)

如果您不想通过arr1来搜索arr2的每一项(制定O(n²)解决方案),则可以为键入以下内容的arr1创建一个查找对象: id。然后,您可以简单地遍历arr2并合并通过查找找到的对象。如果您有更大的数组,这样做会更有效率。

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)

答案 2 :(得分:0)

也许你可以做这样的事情

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

答案 3 :(得分:0)

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

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

首先从arr2创建查找映射,然后在.map()上使用arr1从查找表中分配值。

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' },
// {...},{...} ]