简体   繁体   中英

Merge Nested arrays in Javascript

I am a javascript beginner. I need to merge two arrays which contains objects which in turn contain arrays.

I have two arrays

arr1[
    {
        description : "this is a object",
        array       : [a.x,"b"]
     }
]

arr2[
    {
       array : [a.z,"b","c","d"]               
    } 
]

I have used the following code to perform the merge

function arrayUnique(array) {
    var a = array.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;
}
function combine(obj1,obj2) {
    var res = {};
    for (var k1 in obj1) {
        if (!obj1.hasOwnProperty(k1)) continue;
        if (obj2.hasOwnProperty(k1)) { // collision
            if (typeof(obj1[k1]) !== typeof(obj2[k1])) throw "type mismatch under key \""+k1+"\".";
            if (Array.isArray(obj1[k1])) {
                res[k1] = obj1[k1].concat(obj2[k1]);
            } else if (typeof(obj1[k1]) === 'string' || obj1[k1] instanceof String) {
                res[k1] = arrayUnique(obj1[k1].concat(obj2[k1]));
            } else if (typeof(obj1[k1]) === 'object') {
                res[k1] = combine(obj1[k1],obj2[k1]);
            } else {
                throw "unsupported collision type "+typeof(obj1[k1])+" under key \""+k1+"\".";
            }
        } else {
            res[k1] = obj1[k1];
        }
    }
    for (var k2 in obj2) {
        if (!obj2.hasOwnProperty(k2)) continue;
        if (obj1.hasOwnProperty(k2)) continue; // already handled it above
        res[k2] = obj2[k2];
    }
    return res;
}

var res = combine(arr1,arr2);

This is the result i expect

res = { description : "this is a object", array : [a.x,a.z,"b","c","d"] }

But unfortunately this is the result i get

res = { description : "this is a object", array : [a.x,"b","c","d"]}

az is ommited.

When both objects have the same array field you concatenate them ( concat append the two arrays one after another), here:

 if (Array.isArray(obj1[k1])) {
     res[k1] = obj1[k1].concat(obj2[k1]);

If instead of ["a","a","b","b","c","d"] you want to get ["a","b","c","d"] you need to perform the array merge manually.

Check this answer for multiple ways to merge arrays without duplicates.

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