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

后端 未结 11 1648
渐次进展
渐次进展 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条回答
  •  既然无缘
    2021-02-03 14:57

    You can give this a try.

    var origArr = [
      {name: 'Trump', isRunning: true},
      {name: 'Cruz', isRunning: true},
      {name: 'Kasich', isRunning: true}
    ];
    var updatingArr = [
      {name: 'Cruz', isRunning: false},
      {name: 'Kasich', isRunning: false}
    ];
    
    var origLength = origArr.length;
    var updatingLength = updatingArr.length;
    
    //Traverse the original array and replace only if the second array also has the same value
    for(i = origLength-1; i >= 0; i--) {
        for(j = updatingLength -1; j >= 0; j--) {
        if(origArr[i].name === updatingArr[j].name) {
            origArr[i] = updatingArr[j];
        }
      }
    }
    
    console.log(origArr);
    

提交回复
热议问题