与此问题非常相似: Javascript: how to dynamically create nested objects using object names given by an array
而不是打电话
assign(obj, keyPath, value)
以前回答的使用示例:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
那将输出:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
现在,我想支持数组 ...在上面的示例中,我想支持每个帐户多个地址信息。我想说:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
结果将是:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/
会在括号内显示#,但我不确定如何迭代数组中的每个元素以确保它存在(如果不存在则创建它) )..和困难的部分,支持这个作为功能的一部分提交的每个数组元素(我想说:
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
修改
想出来。
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}