【问题标题】:Build Object path with variables使用变量构建对象路径
【发布时间】:2014-05-26 09:29:51
【问题描述】:
var area = "residenceArea1";
var type = "residenceType1";
var year = "constructionYear1";
var obj = {
    "residenceType1": [
        {
            "constructionYear1": [
                {
                    "residenceArea1": 103,
                    "residenceArea2": 82
                }
            ]
        },
        {
            "constructionYear2": [
                {
                    "residenceArea1": 62
                }
            ]
        }
    ],
    "residenceType2": [
        {
            "constructionYear1": [
                {
                    "residenceArea1": 83
                }
            ]
        }
    ]
};

console.log(object.residenceType1[0].constructionYear1[0].residenceArea1) //103

这个对象更长,但我为这个问题缩短了它。有没有办法让我的 3 个变量设置对象路径?像这样:

console.log(object.type[0].year[0].area)

变量会根据用户选择的单选按钮而变化,这就是我想用变量设置路径的原因。这个对象也可以变得更简单,这样我们就不需要为数组指定[0]了吗?

【问题讨论】:

    标签: javascript jquery arrays javascript-objects


    【解决方案1】:

    我认为你要求的是这样的:

    obj[type][0][year][0][area]
    

    方括号表示法允许在对象的键查找中使用任意表达式。 请注意,在查找过程中,键将始终转换为字符串。

    以下是等价的:

    var type = 'residenceType1';
    
    obj.residenceType1            // dot-notation
    obj['residenceType1']         // square-bracket notation with string expression
    obj[type]                     // square-bracket notation with variable expression
    

    【讨论】:

      【解决方案2】:

      唯一的解决方案是通过 [] 访问并传入命名属性:

      console.log(object[type][0][year][0][area]);
      

      【讨论】:

        猜你喜欢
        • 2020-03-31
        • 2020-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-27
        相关资源
        最近更新 更多