我有
obj1 = {
"prop1":{
"prop12":[
"Process",
"Process Decomposition"
]
}
}
obj2 = {
"prop1":{
"prop12":[
"Process Decomposition"
]
}
}
为什么使用$.extend(true, obj1, obj2)
导致这些:
resObj = {
prop1:{
prop12:["Process Decomposition", "Process Decomposition"]
}
}
我在期待:
resObj = {
prop1:{
prop12:["Process", "Process Decomposition"]
}
}
有人可以建议一种更好的方法来合并/扩展两个数组/对象吗?
答案 0 :(得分:2)
您是否尝试合并prop12阵列?
是
您可以创建新对象,使用for..in
来迭代obj1
,$.merge()
,$.unique()
的属性,以合并obj1.prop1.prop12
和{{1}处的数组从结果数组中删除重复的条目。
obj2.prop1.prop12
var res = $.unique($.merge(obj1.prop1.prop12, obj2.prop1.prop12));
var obj1 = {
"prop1":{
"prop12":[
"Process",
"Process Decomposition"
]
}
};
var obj2 = {
"prop1":{
"prop12":[
"Process Decomposition"
]
}
};
var res = {};
for (var prop in obj1) {
if (!res.hasOwnProperty(prop) && typeof obj1[prop] === "object") {
res[prop] = Object.assign({}, obj1[prop])
}
};
// merge `obj1.prop1.prop12`, `obj2.prop1.prop12` arrays,
// removing duplicates entries
var arr = $.unique($.merge(obj1.prop1.prop12, obj2.prop1.prop12));
// set `res.prop1.prop12` to `arr` array
res.prop1.prop12 = arr;
console.log("\nres:", res, "\n\nobj1:", obj1, "\n\nobj2:", obj2);