用AngularJS深度合并对象

通常我会使用浅拷贝对象 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函数已经执行了我不知道的深度合并?

  • 如果不是,则有一种本机方法可以在javascript中递归地执行n个级别的操作。

回答:

用途angular.merge

不同于extend()merge()递归地进入源对象的对象属性,执行深层复制。

angular.merge(object1, object2); // merge object 2 into object 1


没有理由不应该使用简单的递归算法:)

假设它们都是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;

}

这是一个工作的jsfiddle

(注意,这里不处理数组)

以上是 用AngularJS深度合并对象 的全部内容, 来源链接: utcz.com/qa/416578.html

回到顶部