我正在創建一個提供get()和set()函數以從JavaScript對象讀取和更新值的功能。訣竅是我使用點符號字符串來指定屬性。動態更新/創建對象屬性
我已經get()工作正常,它是set(),我遇到了麻煩。
的樣本數據:
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"
}
有關如何完成此任何想法?
目的是不提供給主叫方,因此get()和()設置。我爲了說明的目的添加了它。感謝您的鏈接,但是...希望它能解決我的問題! –
雖然你的代碼沒有解決我的問題,但鏈接確實如此。謝謝! –