我是一名javascript初学者。我需要合并两个包含对象的数组,这些对象又包含数组。
我有两个数组
int tokenCopy(char *dest, const char *src, int destSize) {
*dest = 0;
// rest of the code
}
我使用以下代码执行合并
arr1[
{
description : "this is a object",
array : [a.x,"b"]
}
]
arr2[
{
array : [a.z,"b","c","d"]
}
]
这是我期待的结果
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);
但不幸的是,这是我得到的结果
res = { description : "this is a object", array : [a.x,a.z,"b","c","d"] }
a.z被忽略了。
答案 0 :(得分:0)
当两个对象具有相同的数组字段时,您将它们连接起来(concat
一个接一个地附加两个数组),这里:
if (Array.isArray(obj1[k1])) {
res[k1] = obj1[k1].concat(obj2[k1]);
如果您希望获得["a","a","b","b","c","d"]
而不是["a","b","c","d"]
,则需要手动执行数组合并。
检查此answer有多种方法来合并没有重复的数组。