如何以编程方式添加到可变嵌套对象中

How can I programmatically add to a variably-nested object?

本文关键字:嵌套 对象 添加 编程 方式      更新时间:2023-09-26

我需要一种方法将一个对象添加到另一个对象中。通常情况下,这很简单,只需要

obj[property] = {'name': bob, 'height': tall}

然而,有问题的对象是嵌套的,因此需要以下内容:

obj[prop1][prop2] = {'name': bob, 'height': tall}

不过,关键是嵌套是可变的。也就是说,我不知道每个新对象在运行时之前嵌套的深度。基本上,我将生成一个字符串,表示像这样的对象路径

"object.secondObj.thirdObj.thurtObj"

然后我需要在第四个对象中设置数据,但我不能使用bracket[]方法,因为我不知道事先需要多少个括号。有办法做到这一点吗?如果有必要的话,我也在使用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;
    }
}

不生成字符串。。。

var o="object";
//code
o+=".secondObj";
//code
o+=".thirdObj";
//code
o+=".fourthObj";

你可以做

var o=object;
//code
o=o.secondObj;
//code
o=o.thirdObj;
//code
o=o.fourthObj;

然后你可以添加这样的数据:

o.myprop='myvalue';

并且object将随着这些变化而更新。

请在此处查看:http://jsfiddle.net/rFuyG/