我需要一种方法来将一个对象添加到另一个对象中。通常这很简单,只需
obj[property] = {'name': bob, 'height': tall}
然而,所讨论的对象是嵌套的,因此需要以下内容:
obj[prop1][prop2] = {'name': bob, 'height': tall}
不过,最重要的是嵌套是可变的。那就是我不知道每个新对象在运行前会嵌套多深。 基本上我将生成一个表示对象路径的字符串,如
“对象.secondObj.thirdObj.fourthObj”
然后我需要在第四个对象中设置数据,但是我不能使用方括号[]方法,因为我事先不知道需要多少个方括号。有没有办法做到这一点? 如果有必要,我也在使用 jQuery。
最佳答案
当然,您可以使用递归或简单迭代。我更喜欢递归。以下示例旨在作为概念验证,可能不应在生产中使用。
var setDeepValue = function(obj, path, value) {
if (path.indexOf('.') === -1) {
obj[path] = value;
return;
}
var dotIndex = path.indexOf('.');
obj = obj[path.substr(0, dotIndex)];
return setDeepValue(obj, path.substr(dotIndex + 1), value);
};
但是递归不是必需的,因为在 JavaScript 中你可以只改变引用。
var objPath = 'secondObj.thirdobj.fourthObj';
var valueToAdd = 'woot';
var topLevelObj = {};
var attributes = objPath.split('.');
var curObj = topLevelObj;
for (var i = 0; i < attributes.length; i++) {
var attr = attributes[i];
if (typeof curObj[attr] === 'undefined') {
curObj[attr] = {};
}
curObj = curObj[attr];
if (i === (attributes.length - 1)) {
// We're at the end - set the value!
curObj['awesomeAttribute'] = valueToAdd;
}
}
关于javascript - 如何以编程方式添加到可变嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206268/