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

后端 未结 11 1521
渐次进展
渐次进展 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('<pre>' + JSON.stringify(origArr, 0, 4) + '</pre>');

    0 讨论(0)
  • 2021-02-03 15:00

    Same as @gevorg answer, but you may want to also add a new object to the original array if no matches are found.

    let combinedEvents = origEvents;
    for(let i =0; i< newEvents.length; i++){
      let newEvent = newEvents[i];
      for(let j =0; j< origEvents.length; j++){
        let origEvent = origEvents[j];
        if(newEvent.events_id == origEvent.events_id){
          combinedEvents.splice(j,1, newEvent);
          break;
        } else if(j === origEvents.length - 1){
          combinedEvents.push(newEvent);
          break;
        }
      }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2021-02-03 15:11

    Here's a solution using underscore:

    var result = _.map(origArr, function(orig){
        return _.extend(orig, _.findWhere(updatingArr, {name: orig.name}));
    });
    
    0 讨论(0)
提交回复
热议问题