javascript - 棘手的 Javascript : how to retrieve value from json dict inside array inside dict :)

标签 javascript json

我的 javascript 中包含一个 json 文件,它定义了一个如下所示的变量:

var places_json = {
  "count": 13476,
  "places": [{
      "area": "London",
      "county": "STS",
      "lat": 52.300151820000004,
      "lon": -2.36665606,
      "code": "7567",
      "id": 1
    },
    {
      "area": "Sheffield",
      "county": "STS",
      "lat": 51.33648680000003,
      "lon": 0.98861179000000001,
      "code": "9919",
      "id": 6
    },
    {
      "area": "Huxton",
      "county": "STS",
      "lat": 53.27483902,
      "lon": -1.0146250700000001,
      "code": "9953",
      "id": 11
    },
  ]
}

我想使用 Javascript 为 id 为 11 的条目检索 area 的值。

有人知道怎么做吗?这对我来说太难了——我的 Javascript 不是那么先进。如果我知道我需要的条目的数组索引,那么我可以这样做:

var entry = json_places.places[i] 

但我不知道,不幸的是,我只知道 id 的值(它是唯一的)。

提前致谢。

最佳答案

function findAreaById(placesArray, id) {    
    var place = null;
    for (var i = 0, length = placesArray.length; i < length; i++) {
        place = placesArray[i]; 
        if (place.id === id) {
            return place.area;
        }
    }
    return null;
}

关于javascript - 棘手的 Javascript : how to retrieve value from json dict inside array inside dict :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2195960/

相关文章:

json - 戈朗 : JSON: How do I unmarshal array of strings into []int64

json - 如何使用带有数字范围的 VBA-JSON 解析数据?

javascript - 简单的无名 json 数组转换为映射的 JS 或 PHP 数组

javascript - CSS 背景大小 : cover and background positioning for a 1000x100 graphic

javascript - 为什么当我使用 @react-google-maps/api 时,react-select 会中断?

javascript - Bootstrap 3 : Nested tabs disappear when another tab is made active

javascript - 如何在 Controller 中格式化 JSON 数据

PHP-需要第一个表中的前3个json数据和第二个表中的所有数据

JavaScript 程序语法错误

javascript - ng-repeat 在悬停时连续发射