You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据脚本存储变量匹配键值对从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);

代码说明

  1. 读取并解析locations.json文件内容,转为JavaScript数组
  2. 定义需要匹配的目标值targetWeather和targetDistance
  3. 通过filter()方法遍历数组,仅保留同时满足两个条件的对象:
    • Distance (带空格)的值等于4
    • Weather的值等于hot
  4. 最终matchedLocations就是筛选后的结果数组

输出结果

执行代码后会得到以下符合条件的对象数组:

[
  {
    "Distance ": 4,
    "Weather": "hot"
  },
  {
    "Distance ": 4,
    "Weather": "hot"
  }
]

内容的提问来源于stack exchange,提问作者tomhuckle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:38:14