我有以下对象:
var object = {
"property1": "value1",
"property2": "value2",
"subobject": {
"property1": "value1",
"property2": "value2",
"subobject": {
"property1": "value1",
"property2": "value2",
"subobject": {...
}
}
}
}
我正在尝试设置其中一个嵌套子对象属性,但嵌套级别是动态的。
如何动态设置其中一个嵌套属性而不执行以下操作:object.subobject.subobject = { ... }
?
修改 所以更具体一点,我试图设置一个嵌套的子对象,但我不会每次都知道哪一个。
答案 0 :(得分:5)
让我们使用递归!
function setNest(obj, level, val){
if(level > 0){
setNest(obj.subobject, level-1, val);
}
else{
obj.subobject = val;
}
}
然后称之为:
setNest(object, 2, {a: 12});
答案 1 :(得分:4)
使用递归 - 重构(感谢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!!!');
由于
答案 2 :(得分: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}}
答案 3 :(得分:0)
您可以尝试使用Immutable.js,如下所示:
var immutableJsObject = Immutable.fromJS({
inputs: {
firstDepthNumberOne: {
secondDepth: 'secondDepthValue'
},
firstDepthNumberTwo: 'hello'
}
});
var newImmutableJsObject = immutableJsObject.setIn('inputs.firstDepthNumberOne.secondDepth'.split('.'), 'newValue');
newImmutableJsObject.toJS();