How to merge two arrays of JSON objects - removing duplicates and preserving order in Javascript/jQuery?

后端 未结 4 699
自闭症患者
自闭症患者 2020-12-29 12:38

jsfiddle link: http://jsfiddle.net/vN6fn/1/

Assume I have these 2 objects:

var obj1 = { data: [ 
                      {id:1, commen         


        
4条回答
  •  误落风尘
    2020-12-29 13:19

    Merge two array of objects removing duplicates

    • Using Es6 map() and filter() method

    var obj1 = { data: [ 
                          {id:1, comment:"comment1"},
                          {id:2, comment:"comment2"},
                          {id:3, comment:"comment3"}
                       ] }
    
    var obj2 = { data: [ 
                          {id:2, comment:"comment2"},
                          {id:3, comment:"comment3"},
                          {id:4, comment:"comment4"}
                        ]}
    let obj3 = [...obj1.data, ...obj2.data]
    
    function mergeUniqueArray(arr, comp) {
    
      let unique = arr
        .map(item => item[comp])
    
         // store the keys of the unique objects
        .map((item, i, final) => final.indexOf(item) === i && i)
    
        // eliminate the duplicate keys & store unique objects
        .filter(item => arr[item]).map(item => arr[item]);
        
       return unique;
    }
    
    console.log(mergeUniqueArray(obj3,'id'));

提交回复
热议问题