JavaScript - merge two arrays of objects and de-duplicate based on property value

后端 未结 11 1532
渐次进展
渐次进展 2021-02-03 14:36

I want to update (replace) the objects in my array with the objects in another array. Each object has the same structure. e.g.

var origArr = [
          


        
11条回答
  •  梦毁少年i
    2021-02-03 14:46

    const origArr = [
      {name: 'Trump', isRunning: true},
      {name: 'Cruz', isRunning: true},
      {name: 'Kasich', isRunning: true}
    ];
    
    const updatingArr = [
      {name: 'Cruz', isRunning: false},
      {name: 'Kasich', isRunning: false}
    ];
    
    let hash = {};
    
    for(let i of origArr.concat(updatingArr)) {
      if(!hash[i]) {
        hash[i.name] = i;
      }
    }
    
    let newArr = [];
    
    for(let i in hash) {
      newArr.push(hash[i])
    }
    
    console.log(newArr);
    

提交回复
热议问题