使用不同的键迭代Json

时间:2017-02-20 02:02:46

标签: javascript json

如何循环浏览此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"
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您可以使用for..of循环,Object.entries()来迭代对象的属性名称和值;如果值id24匹配,则将变量设置为该对象的属性名称; 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);