通常对于浅拷贝对象我会使用angular.extend()
举个例子:
var object1 = {
"key": "abc123def456",
"message": {
"subject": "Has a Question",
"from": "example1@example.com",
"to": "example2@example.com"
}
};
var object2 = {
"key": "00700916391"
};
console.log(angular.extend({}, object1, object2));
会给我们:
{
"key": "00700916391",
"message": {
"subject": "Has a Question",
"from": "example1@example.com",
"to": "example2@example.com"
}
}
但是如果我想合并对象以便父键不被子对象覆盖怎么办:
var object1 = {
"key": "abc123def456",
"message": {
"subject": "Has a Question",
"from": "example1@example.com",
"to": "example2@example.com"
}
};
var object2 = {
"key": "00700916391", //Overwrite me
"message": { //Dont overwrite me!
"subject": "Hey what's up?", //Overwrite me
"something": "something new" //Add me
}
};
console.log(merge(object1, object2));
会给我们:
{
"key": "00700916391",
"message": {
"subject": "Hey what's up?",
"from": "example1@example.com",
"to": "example2@example.com",
"something": "something new"
}
}
是否有 Angular 函数已经进行了我不知道的深度合并?
如果没有,是否有一种 native 方法可以在 javascript 中递归执行 n 级深度?
最佳答案
Angular 1.4 或更高版本
使用angular.merge
:
Unlike
extend()
,merge()
recursively descends into object properties of source objects, performing a deep copy.
angular.merge(object1, object2); // merge object 2 into object 1
旧版本的 Angular:
简单的递归算法没有理由不能工作:)
假设它们都是 JSON.stringify 或类似的结果:
function merge(obj1,obj2){ // Our merge function
var result = {}; // return result
for(var i in obj1){ // for every property in obj1
if((i in obj2) && (typeof obj1[i] === "object") && (i !== null)){
result[i] = merge(obj1[i],obj2[i]); // if it's an object, merge
}else{
result[i] = obj1[i]; // add it to result
}
}
for(i in obj2){ // add the remaining properties from object 2
if(i in result){ //conflict
continue;
}
result[i] = obj2[i];
}
return result;
}
Here is a working fiddle
(注意,这里不处理数组)
关于javascript - 使用 AngularJS 深度合并对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242927/