设置嵌套对象值 [英] Setting a nested object value

查看:86
本文介绍了设置嵌套对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

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

我试图设置一个嵌套的子对象属性,但嵌套级别是动态的。

I am trying to set one of the nested subobject properties, but the nested level is dynamic.

如何在不执行此操作的情况下动态设置其中一个嵌套属性: object.subobject.subobject = {...}

How can I dynamically set one of these nested properties without doing something like this: object.subobject.subobject = { ... }?

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

So to be more specific, I am trying to set one of the nested subobjects, but I won't know which one each time.

推荐答案

让我们使用递归!

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

然后称之为:

setNest(object, 2, {a: 12});

这篇关于设置嵌套对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆