首页 > 解决方案 > 脚本如何计算包含 json 数据中指定频率的对象

问题描述

我有一个数据 json 格式(population.json):

[
{
    "Population": "100",
    "City": "London",
    "Date": "2020-08-07",
    "Long": "70",
     "Lat": "20.55"
},
{
    "Population": "500",
    "City": "Manchester",
    "Date": "2020-08-07",
    "Long": "70",
     "Lat": "26.55"
},
{
    "Population": "800",
    "City": "Manchester",
    "Date": "2020-08-07",
    "Long": "70",
     "Lat": "26.55"
},
{
    "Population": "800",
    "City": "London",
    "Date": "2020-08-07",
    "Long": "70",
     "Lat": "26.55"
},
]

我想知道曼彻斯特市的人口频率 > 100 和所有城市的人口频率 > 100 吗?

我尝试使用以下脚本:

<body>
 <p>
 frequency of Population > 100 in Manchester : <span id="population"></span>
 </p>
 </body>

对于 javascript:

<script>
var jsonData = 'population.json';
            function getJSONValue(fileJSON) {
                var value = $.ajax({
                    url: fileJSON,
                    async: false
                }).responseText;
                return value
            }
            populationData = getJSONValue(jsonData)
            var populationDataJSON = JSON.parse(populationData)
for (k = 0; k < populationDataJSON.length; k++) {
                var population_data = parseInt(populationDataJSON[k].population)
                var Coordinate = new L.latLng(([populationDataJSON[k].Lat, populationDataJSON[k].Long]))
                if (population > 100) {              }
                else { }
            }

如何完成此脚本以获得我想要的结果

标签: javascript

解决方案


最简单的方法是使用forEach

const populationDataJSON = [{
    "Population": "100",
    "City": "London",
    "Date": "2020-08-07",
    "Long": "70",
    "Lat": "20.55"
  },
  {
    "Population": "500",
    "City": "Manchester",
    "Date": "2020-08-07",
    "Long": "70",
    "Lat": "26.55"
  },
  {
    "Population": "800",
    "City": "Manchester",
    "Date": "2020-08-07",
    "Long": "70",
    "Lat": "26.55"
  },
  {
    "Population": "800",
    "City": "London",
    "Date": "2020-08-07",
    "Long": "70",
    "Lat": "26.55"
  },
];

populationDataJSON.forEach(k => {
  const population_data = k["Population"];

  if (population_data > 100) console.log(k);
})

k这里代表每个对象实例,因此您可以像访问它的属性一样populationDataJSON[k]


推荐阅读