Having two JSON formatted js-objects:
有两个JSON格式的js-objects:
obj1 = { prop1: 1,
prop2: 2,
prop3: 3 }
obj2 = { prop1: 1,
prop2: 3 }
What is the best js-practise to update obj2 into obj1, that also removes properties? Typically in a jQuery/angular context. Resulting in:
将obj2更新为obj1的最佳js实践是什么,这也删除了属性?通常在jQuery / angular上下文中。导致:
obj1 = { prop1: 1, // not updated, nor overwritten
prop2: 3 // updated
} // prop3 removed
Must also deal with nested objects and arrays.
还必须处理嵌套对象和数组。
3 个解决方案
#1
1
Try this:
function merge_objects(obj1,obj2){
for (var attr in obj2) { obj1[attr] = obj2[attr]; }
for (var attr in obj1) { if(!obj2[attr]){ delete obj1[attr]} }
return obj1;
}
#2
1
To compare objects you can use angular.equals(obj1, obj2). For merging you can check angular.extend but it won't delete missing elements.
要比较对象,可以使用angular.equals(obj1,obj2)。对于合并,您可以检查angular.extend,但不会删除缺少的元素。
#3
0
If you want to copy(or clone including arrays/child objects) contents of object2 into object1, try using jquery extend()
如果要将object2的内容(或克隆包括数组/子对象)复制到object1,请尝试使用jquery extend()
Please find jsfiddle [here][2]
#1
1
Try this:
function merge_objects(obj1,obj2){
for (var attr in obj2) { obj1[attr] = obj2[attr]; }
for (var attr in obj1) { if(!obj2[attr]){ delete obj1[attr]} }
return obj1;
}
#2
1
To compare objects you can use angular.equals(obj1, obj2). For merging you can check angular.extend but it won't delete missing elements.
要比较对象,可以使用angular.equals(obj1,obj2)。对于合并,您可以检查angular.extend,但不会删除缺少的元素。
#3
0
If you want to copy(or clone including arrays/child objects) contents of object2 into object1, try using jquery extend()
如果要将object2的内容(或克隆包括数组/子对象)复制到object1,请尝试使用jquery extend()
Please find jsfiddle [here][2]