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

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

    This version lets you define the selector that defines an object as duplicate.

    • forEach iterates over the new data
    • findIndex returns an index >= 0 if two selectors are equal. If none are equal, it returns -1
    • If there is a duplicate, we use slice to replace the original by the new.
    • If there's no duplicate, we push it into the original array.

    const origArr = [
      {name: 'Trump', isRunning: true},
      {name: 'Cruz', isRunning: true},
      {name: 'Kasich', isRunning: true}
    ];
    
    const updatingArr = [
      {name: 'Cruz', isRunning: false},
      {name: 'Kasich', isRunning: false}
    ];
    
    const mergeArrayOfObjects = (original, newdata, selector = 'key') => {
    	newdata.forEach(dat => {
    		const foundIndex = original.findIndex(ori => ori[selector] == dat[selector]);
    		if (foundIndex >= 0) original.splice(foundIndex, 1, dat);
            else original.push(dat);
    	});
    
    	return original;
    };
    
    const result = mergeArrayOfObjects(origArr, updatingArr, "name")
    console.log('RESULT -->', result)

提交回复
热议问题