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

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

    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;
        }
      }
    }
    

提交回复
热议问题