0

我有类似的东西:

var object1 = { 'tab1' : [{ test : 10 }, { test : 15 }], 'tab2' : [{ test : 15 }] };

var object2 = { 'tab2' : [{ test : 35 }, { test : 25 }], 'tab3' : [{ test : 40 }] };

我需要结果:

var object3 = { 
    'tab1' : [{ test : 10 }, { test : 15 }],
    'tab2' : [{ test : 35 }, { test : 25 }, { test : 15 }],
    'tab3' : [[{ test : 40 }]
};

我怎样才能做到这一点?

$.extend(true, object1, object2)返回没有{ test : 15 }in 的对象tab2

4

1 回答 1

2

我会在这里使用javascript,比如

var merged = [];
for (var key in object1) {
    if (object1.hasOwnProperty(key)){
       var obj1Arr, obj2Arr;
       obj1Arr = object1[key];
       obj2Arr = object2[key];

       if (obj1Arr) merged = merged.concat(obj1Arr);
       if (obj2Arr) merged = merged.concat(obj2Arr);
       object3[key] = merged;
        merged = [];
    }
}

for (var key in object2) {
    if (object2.hasOwnProperty(key) && !object3[key]){ // ignore the keys we already found
       var obj1Arr, obj2Arr;
       obj1Arr = object1[key];
       obj2Arr = object2[key];

       if (obj1Arr) merged = merged.concat(obj1Arr);
       if (obj2Arr) merged = merged.concat(obj2Arr);
       object3[key] = merged;
       merged = []; 
    }
}

console.log(object3) 和小提琴

http://jsfiddle.net/H4UGb/1/

您可以通过将 if 语句中的通用代码放入函数中来稍微清理一下...

于 2013-03-15T17:41:48.470 回答