Reputation: 3
How would I go about looping through this JSON object to find a specific "id" key, and give back the name "outer key"? Sorry, I'm not too familiar with the proper name.
ie, search for the id '24', and get 'Jax' in Javascript?
{
"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"
]
}
}
}
Upvotes: 0
Views: 97
Reputation: 1
You can use for..of
loop, Object.entries()
to iterate property names and values of an object; if value id
matches 24
, set variable to property name of that object; break
loop or return property from within if
statement.
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);
Upvotes: 1