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

后端 未结 11 1523
渐次进展
渐次进展 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 15:00

    This will do what you need:

    var origArr = [
      {name: 'Trump', isRunning: true},
      {name: 'Cruz', isRunning: true},
      {name: 'Kasich', isRunning: true}
    ];
    
    var updatingArr = [
      {name: 'Cruz', isRunning: false},
      {name: 'Kasich', isRunning: false}
    ];
    
    for (var i = 0; i < updatingArr.length; ++i) {
      var updateItem = updatingArr[i];
      for (var j = 0; j < origArr.length; ++j) {
        var origItem = origArr[j];
        if (origItem.name == updateItem.name) {
          origItem.isRunning = updateItem.isRunning;
          break;    
        }
      }
    }
    
    document.write('
    ' + JSON.stringify(origArr, 0, 4) + '
    ');

提交回复
热议问题