4

我有以下对象:

var object = {
    "property1": "value1",
    "property2": "value2",
    "subobject": {
        "property1": "value1",
        "property2": "value2",
        "subobject": {
            "property1": "value1",
            "property2": "value2",
            "subobject": {...
            }
        }
    }
}

我正在尝试设置嵌套子对象属性之一,但嵌套级别是动态的。

如何在不执行以下操作的情况下动态设置这些嵌套属性之一:object.subobject.subobject = { ... }

编辑: 所以更具体地说,我正在尝试设置嵌套子对象之一,但我每次都不知道是哪一个。

4

4 回答 4

7

使用递归 - 重构(感谢 Rocket Hazmat)

这个功能对我有用!:

/**
 * @obj: the json object to change
 * @access: string dot separates route to value
 * @value: new valu
 */
function setValue(obj,access,value){
    if (typeof(access)=='string'){
        access = access.split('.');
    }
    if (access.length > 1){
        setValue(obj[access.shift()],access,value);
    }else{
        obj[access[0]] = value;
    }
}

有一个对象:

var jsonObject = {
    'name' : 'pepe',
    'links' : 
        {
        'link1' : 'one',
        'link2' : 'two',
        'link3' : 
            {
            'link31' : '3url',
            'link32' : '3url',
            'link33' : '3url'
            }
        }
 }

我们可以通过以下方式轻松更改值:

 setValue(jsonObject,'links.link3.link32','new value!!!');

谢谢

于 2014-08-12T10:04:25.883 回答
5

让我们使用递归!

function setNest(obj, level, val){
    if(level > 0){
        setNest(obj.subobject, level-1, val);
    }
    else{
        obj.subobject = val;
    }
}

然后这样称呼它:

setNest(object, 2, {a: 12});
于 2012-06-15T16:47:41.993 回答
0

您可以定义自己的 Object 方法;为了简洁起见,我也使用下划线:

var _ = require('underscore');

// a fast get method for object, by specifying an address with depth
Object.prototype.pick = function(addr) {
    if (!_.isArray(addr)) return this[addr]; // if isn't array, just get normally
    var tmpo = this;
    while (i = addr.shift())
        tmpo = tmpo[i];
    return tmpo;
};
// a fast set method for object, put value at obj[addr]
Object.prototype.put = function(addr, val) {
    if (!_.isArray(addr)) this[addr] = val; // if isn't array, just set normally
    this.pick(_.initial(addr))[_.last(addr)] = val;
};

示例用法:

var obj = { 
           'foo': {
                   'bar': 0 }}

obj.pick('foo'); // returns { bar: 0 }
obj.pick(['foo','bar']); // returns 0
obj.pick('foo.bar'.split('.')); // equivalent as above, returns 0
obj.put(['foo', 'bar'], -1) // obj becomes {'foo': {'bar': -1}}
于 2015-05-27T15:14:31.587 回答
0

您可以尝试使用Immutable.js,如下所示:

var immutableJsObject = Immutable.fromJS({
  inputs: {
    firstDepthNumberOne: {
      secondDepth: 'secondDepthValue'
    },
    firstDepthNumberTwo: 'hello'
  }
});

var newImmutableJsObject = immutableJsObject.setIn('inputs.firstDepthNumberOne.secondDepth'.split('.'), 'newValue');

newImmutableJsObject.toJS();
于 2016-04-04T00:34:39.980 回答