如何循环浏览此JSON对象以查找特定的“id”键,并将名称“外键”返回?对不起,我不太熟悉正确的名字。
即搜索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"
]
}
}
}
答案 0 :(得分:1)
您可以使用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);