简体   繁体   中英

merge two javascript objects that contain arrays

I have the following...

array [
       obj1 = {key1: a,
               key2: [a, b, c]
               },

       obj2 = {key2: [c, d]}
];

And want the following outcome...

array[
       obj1 = {key1: a,
               key2: [a, b, c, d]
               }
]

How can I merge obj1 and obj2 so that key2 contains no duplicates?

Thanks! I am also already using jQuery

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};   

var mergedArray = array1.concat(array2).unique();

via this question - How to merge two arrays in Javascript and de-duplicate items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM