我有类似的东西:
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 }
tab2
的对象
答案 0 :(得分: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) 还有一个小提琴
你可以通过将if语句中的公共代码放入函数中来清理它......