javascript - 脚本如何计算包含 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 { }
}
如何完成此脚本以获得我想要的结果
解决方案
最简单的方法是使用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]
:
推荐阅读
- excel - VBA 扩展范围
- hibernate - 使用 Spring Boot 2.1+ 为 Hibernate 配置缓存
- javascript - Typescript - 如何在不使用 Exclude<> 的情况下从泛型类型中排除类型?
- ssl - 鱿鱼和其他 SSL_ports
- node.js - 安装 Node.js 后,'npm' 未被识别为内部或外部命令、可运行程序或批处理文件 - Windows
- java - 为什么在构造函数创建之前没有初始化实例变量。如果它们在类加载本身时被初始化会发生什么
- amazon-web-services - 在 aws sagemaker 中为多个数据集托管多个模型
- react-native-android - 如何使用 swiper flatlist 在本机反应中获取数组中的对象
- pdf - PDFTron full api 未在 WebViewer 中加载
- javascript - 如何使硒滚动以查看元素的能力