我在发布问题之前搜索stackoverflow,但我找不到任何解决方案。我有一个像这样的对象:
"{"COURRIERS":
{"05. Juridique":
[{"res_id":100,"type_label":"Plainte","subject":"test23","doctypes_first_level_label":"COURRIERS","doctypes_second_level_label":"05. Juridique","folder_level":2}]
}
}"
我需要像数组一样访问它,以获取res_id等信息。
我该怎么做?
提前致谢
答案 0 :(得分:2)
假设您在每个图层中都不会有多个对象/数组,这可以满足您的需求。
let obj = {
"COURRIERS": {
"05. Juridique": [{
"res_id": 100,
"type_label": "Plainte",
"subject": "test23",
"doctypes_first_level_label": "COURRIERS",
"doctypes_second_level_label": "05. Juridique",
"folder_level": 2
}]
}
}
let folder = Object.keys(obj)[0]
let type = Object.keys(obj[folder])[0]
let result = obj[folder][type][0]
console.log(result)

答案 1 :(得分:1)
那样的东西?
(我在变量中插入数据并用键索引打印想要的结果)
let obj = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}
};
console.log(obj["COURRIERS"]["05. Juridique"][0]["res_id"]);

修改强>
你想用变量来访问它。 为避免bug,我强烈建议您检查数组/对象中是否存在变量值键,如:
let folder = 'COURRIERS';
if(folder.indexOf(data) >= 0) { // folder.indexOf(data) = 0
// ... finish the job here :)
}
// indexOf return -1 if the value is not found
答案 2 :(得分:1)
您可以通过多种方式访问数据。以下内容将有助于阐明您访问某些数据的一些方法。
myObj.type = "Dot syntax";
myObj.type = "Dot syntax";
myObj["date created"] = "String with space";
myObj[str] = "String value";
myObj[rand] = "Random Number";
myObj[obj] = "Object";
myObj[""] = "Even an empty string";
对于您的问题,您可以使用以下
var x = {
"COURRIERS":{
"05. Juridique":[
{
"res_id":100,
"type_label":"Plainte",
"subject":"test23",
"doctypes_first_level_label":"COURRIERS",
"doctypes_second_level_label":"05. Juridique",
"folder_level":2
}
]
}};
console.log(x['COURRIERS']['05. Juridique'][0].res_id)