我想要更新一个对象,它可能如下所示:
currentObject = {
someValue : "value",
myObject : {
attribute1 : "foo",
attribute2 : "bar"
}
};
。。具有包含某些更改的对象,例如:
updateObject = {
myObject : {
attribute2 : "hello world"
}
};
最后,我想更新一下currentObject,以便:
currentObject.myObject.attribute2 == "hello world"
对于其他对象,这也应该是可能的。作为一种解决方案,我考虑在对象上迭代,并以某种方式处理命名空间。但我想知道是否有一个简单的解决方案,通过使用一个库,如jQuery或prototype。
发布于 2012-09-22 00:23:32
function update(obj/*, …*/) {
for (var i=1; i<arguments.length; i++) {
for (var prop in arguments[i]) {
var val = arguments[i][prop];
if (typeof val == "object") // this also applies to arrays or null!
update(obj[prop], val);
else
obj[prop] = val;
}
}
return obj;
}
应该做到这一点:update(currentObject, updateObject)
。您可能想要添加一些类型检查,如Object(obj) === obj
,以便只扩展具有真实对象的真实对象,对数组或hasOwnProperty
测试使用正确的循环。
发布于 2016-03-16 10:08:19
下面是一个Object.keys
和递归示例:
// execute object update function
update(currentObject, updateObject)
// instantiate object update function
function update (targetObject, obj) {
Object.keys(obj).forEach(function (key) {
// delete property if set to undefined or null
if ( undefined === obj[key] || null === obj[key] ) {
delete targetObject[key]
}
// property value is object, so recurse
else if (
'object' === typeof obj[key]
&& !Array.isArray(obj[key])
) {
// target property not object, overwrite with empty object
if (
!('object' === typeof targetObject[key]
&& !Array.isArray(targetObject[key]))
) {
targetObject[key] = {}
}
// recurse
update(targetObject[key], obj[key])
}
// set target property to update property
else {
targetObject[key] = obj[key]
}
})
}
JSFiddle demo (打开控制台)。
https://stackoverflow.com/questions/12534238
复制相似问题