我有一个像这样的对象
var userobj = {
user1: {
firstName: 'abc',
lastName: 'abc',
age: 29,
address: {
company: {
location: 'xyz',
city: 'xyz',
street: 'xyz',
city: 'xyz'
},
location: 'xyz',
city: 'xyz',
street: 'xyz',
city: 'xyz'
},
payment: {
visa: false,
master: false,
paypal: true
},
},
user2: {
firstName: 'abc',
lastName: 'abc',
age: 29,
address: {
company: {
location: 'xyz',
city: 'xyz',
street: 'xyz',
city: 'xyz'
},
location: 'xyz',
city: 'xyz',
street: 'xyz',
city: 'xyz'
},
payment: {
visa: false,
master: false,
paypal: true
}
}
};
我想编写一个动态更改数据的函数,就像这个Funtkion
一样function updateUserData(userName, key, value) {
userobj[userName][key] = value;
}
仅在更改第一级键
时有效updateUserData('user1', 'firstName', 'David');
有人可以告诉我如何更改功能,以便我可以将密钥更改为其他级别吗?也许用数组作为参数?喜欢这个
updateUserData('user1', ['address', 'company', 'location'], 'David');
答案 0 :(得分:4)
function updateUserData(userName, keys, value) {
var obj = userobj[userName];
for(var i=0; i<keys.length-1; i++){
obj = obj[keys[i]];
}
obj[keys[i]] = value;
}
答案 1 :(得分:1)
我知道设置嵌套属性的最简单方法是提供该属性的路径并附带新值。
一个简单的实现可能是:
function ObjectWrapper (obj) {
this.object = obj;
this.pattern = new RegExp(/^[[a-z\._]]+$/i);
// set a property at the given path
this.setPropertyValue = function (path, value) {
if (this.pattern.test(path)) {
eval('this.object.' + path + '=' + JSON.stringify(value));
}else{
throw new Error('Malformed property path');
}
}
}
用法:
var obj = {
name: 'Bob',
friends: {
name: 'Joe'
}
};
var wrapper = new ObjectWrapper(obj);
wrapper.setPropertyValue('friends.name', 'Rick');
答案 2 :(得分:0)
该实现的正则表达式是错误的,现在可以正常工作
function ObjectWrapper(obj) {
this.object = obj;
this.pattern = new RegExp(/^[[a-z\._]+$/i);
// set a property at the given path
this.setPropertyValue = (path, value) => {
if (this.pattern.test(path)) {
eval('this.object.' + path + '=' + JSON.stringify(value));
} else {
throw new Error('Malformed property path');
}
};
}
用法:
var obj = {
name: 'Bob',
friends: {
name: 'Joe'
}
};
var wrapper = new ObjectWrapper(obj);
wrapper.setPropertyValue('friends.name', 'Rick');