假设我有以下对象:
var jsonObj = {
"response":{
"result":{
"status":{
"name": "Eric"
}
}
}
}
现在我想动态访问嵌套属性:
jsonKey = "response.result.status.name";
console.log("the status is: " + jsonObj.jsonKey); //I cannot call jsonObj.jsonKey here
有没有办法实现这个目标?
答案 0 :(得分:2)
您无法像预期的那样简单地访问深层嵌套的属性。相反,您需要使用obj[propertyNameAsString]
语法逐一深入了解响应。
这是实现目标的一种方式:
let response = {
"response": {
"method": "GetStatus",
"module": "Module",
"data": null,
"result": {
"status": {
"name": "Eric"
},
"id": 1
},
"result_code": {
"error_code": 0
}
}
}
let keyString = "response.result.status.name"
let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ]
var result = response;
for (key of keyArray) {
result = result[key]
}
console.log(result)

请注意,如果keyArray
中的某个字符串不存在于前一个对象的属性中,则这不是故障保护。