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

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

    Using a double for loop and splice you can do it like so:

    for(var i = 0, l = origArr.length; i < l; i++) {
        for(var j = 0, ll = updatingArr.length; j < ll; j++) {
            if(origArr[i].name === updatingArr[j].name) {
                origArr.splice(i, 1, updatingArr[j]);
                break;
            }
        }
    }
    

    Example here

提交回复
热议问题