动态更新/创建对象属性 [英] Update/Create object properties dynamically
本文介绍了动态更新/创建对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个提供get()和set()函数的功能,以便从JavaScript对象中读取和更新值。诀窍是我使用带点标记的字符串来指定属性。
I'm creating a feature that provides a get() and set() function to read and update values from a JavaScript object. The trick is that I'm using a dot notated string to specify the properties.
我的get()工作正常,它是我的set()我遇到了麻烦。
I've got the get() working fine, it's the set() that I'm having troubles with.
示例数据:
var data = {
person: {
name: 'Fred',
birthday: '19840101',
address: {
street: '123 Main St.',
city: 'Anytown',
state: 'NY',
zip: '123123'
},
family: {
spouse: 'Sally',
children: ['Sam', 'Frank', 'Susan']
}
}
};
get()函数:
function get (path) {
var parts = path.split('.'),
tmp = data;
for (var i = 0, l = parts.length; i < l; ++i) {
if (tmp[parts[i]]) {
tmp = tmp[parts[i]];
}
else {
tmp = null
break;
}
}
return tmp;
}
console.log(get('person.name')); // Fred
console.log(get('person.family.children')); // ['Sam', 'Frank', 'Susan']
console.log(get('person.jobs.apple')); // null
set()函数:
var foo = null;
function set (path, val) {
var parts = path.split('.')
tmp = {},
foo = data;
for (var i = 0, l = parts.length; i < l; ++i) {
if (tmp[parts[i]]) {
tmp = data[parts[i]];
}
else {
tmp = {};
}
if (i+1 === l) {
tmp = val;
}
data[parts[i]] = tmp;
}
}
set('person.name', 'Dave'); // replace existing name
set('person.family.children', ['Tim', 'Matt', 'Kathy']); // replace existing array
set('person.jobs.apple', 'developer'); // should create the necessary properties
console.log(data);
我最终得到以下物品:
obj = {
person: {},
name: "Dave",
family: {},
children: ["Tim","Matt","Kathy"],
jobs: {},
apple: "developer"
}
关于如何做到这一点的任何想法?
Any thoughts on how to accomplish this?
推荐答案
你没有真的需要任何功能。
You do not really need any functions at all for this.
看到这个
var data = {
person: {
name: 'Fred',
birthday: '19840101',
address: {
street: '123 Main St.',
city: 'Anytown',
state: 'NY',
zip: '123123'
},
family: {
spouse: 'Sally',
children: ['Sam', 'Frank', 'Susan']
}
}
};
alert(data.person.name);
data['person']['name'] = 'Tim';
alert(data['person']['name']);
还有这个答案可能会有所帮助
There is also this answer which may help
这篇关于动态更新/创建对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文