如何根据脚本存储变量匹配键值对从JSON文件获取数据
筛选JSON中匹配指定键值对的对象
核心思路
用数组的filter()方法遍历JSON数据,逐一校验每个对象的键值是否与预设变量匹配,注意JSON里的Distance 键带有末尾空格,必须和脚本中的变量引用对应一致。
代码示例(JavaScript)
// Node.js环境读取JSON文件 const fs = require('fs'); const locations = JSON.parse(fs.readFileSync('locations.json', 'utf8')); // 预设匹配条件的变量 const targetWeather = 'hot'; const targetDistance = 4; // 筛选符合条件的对象 const matchedLocations = locations.filter(item => { return item['Distance '] === targetDistance && item.Weather === targetWeather; }); console.log(matchedLocations);
代码说明
- 读取并解析
locations.json文件内容,转为JavaScript数组 - 定义需要匹配的目标值
targetWeather和targetDistance - 通过
filter()方法遍历数组,仅保留同时满足两个条件的对象:Distance(带空格)的值等于4Weather的值等于hot
- 最终
matchedLocations就是筛选后的结果数组
输出结果
执行代码后会得到以下符合条件的对象数组:
[ { "Distance ": 4, "Weather": "hot" }, { "Distance ": 4, "Weather": "hot" } ]
内容的提问来源于stack exchange,提问作者tomhuckle
相关产品推荐
相关产品推荐

