我如何循环遍历这个 JSON 对象来查找特定的“id”键,并返回名称“outer key”?抱歉,我不太熟悉正确的名称。
即,搜索 id“24”,并在 Javascript 中获取“Jax”?
{
"type":"champion",
"version":"7.2.1",
"data":{
"Jax":{
"id":24,
"key":"Jax",
"name":"Jax",
"title":"Grandmaster at Arms",
"tags":[
"Fighter",
"Assassin"
]
},
"Sona":{
"id":37,
"key":"Sona",
"name":"Sona",
"title":"Maven of the Strings",
"tags":[
"Support",
"Mage"
]
}
}
}
最佳答案
您可以使用for..of
循环、Object.entries()
来迭代对象的属性名称和值;如果值 id
匹配 24
,则将变量设置为该对象的属性名称; break
循环或从 if
语句中返回属性。
function getData(json, _id) {
let prop = `${_id} not found`;
for (let [key, value] of Object.entries(json)) {
let {id} = value;
if (id && id === _id) {
return key
}
}
return prop;
}
let res = getData(json.data, 24);
关于javascript - 使用不同的键迭代 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335348/