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

后端 未结 11 1526
渐次进展
渐次进展 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:49

    You can use a hash which gives the index by name, and Object.assign to update.

    var hash = origArr.reduce(function(hash, obj, index) {
      hash[obj.name] = index;
      return hash;
    }, Object.create(null));
    for(var obj of updatingArr) {
      Object.assign(origArr[hash[obj.name]], obj);
    }
    

提交回复
热议问题