使用键数组访问JSON对象

时间:2019-07-11 15:00:40

标签: javascript json

我需要使用通用函数访问myObject。

数据:

myObject = {
    "name": "Caroline",
    "number": 32,
    "country": {
        "province": {
            "city": {
                "NY": 67989876,
                "Boston": 454346,
            }
        }
    }
}

myArray = ["country", "province", "city"]

解决方案是:

myObject["country"]["province"]["city"]

我要在myObject之后重写,那么解决方案不能是副本

myObject["country"]["province"]["city"] = "New datas"

1 个答案:

答案 0 :(得分:1)

var data = myObject;
for (var i in myArray) {
    data = data[myArray[i]];
}

alert(data);

提琴https://jsfiddle.net/g2uyb8rn/

@JeremyThille的更短版本是:

var data = myObject;
for (let i of myArray) data = data[i];

alert(data);