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

如何在JavaScript中筛选JSON文件里state为distinct的对象?

在JavaScript中提取state为distinct的JSON对象

实现步骤

  1. 修正JSON格式(若为字符串形式):标准JSON要求属性名必须用双引号包裹,先调整你的JSON字符串使其符合规范。
  2. 解析JSON(若为字符串):用JSON.parse()将JSON字符串转换为JavaScript数组。
  3. 筛选目标对象:利用数组的filter()方法,过滤出state属性值等于distinct的元素。

代码示例

场景1:数据已是JavaScript数组

// 假设数据已转为JS数组
const data = [
  {path1:"xyz",path2: "xyz2",file1: "filea",file2: "fileb", state: "equal"},
  {path1:"xyz",path2: "xyz2",file1: "filec",file2: "filed",state: "distinct"},
  {path1:"xyz",path2: "xyz2",file1: "filee",file2: "filef",state: "equal"},
  {path1:"xyz4",path2: "xyz3",file1: "fileg",file2: "fileh",state: "distinct"}
];

// 筛选state为distinct的对象
const distinctItems = data.filter(item => item.state === 'distinct');

// 查看结果
console.log(distinctItems);

场景2:数据是JSON字符串

// 修正后的合法JSON字符串
const jsonString = `[
  {"path1":"xyz","path2": "xyz2","file1": "filea","file2": "fileb", "state": "equal"},
  {"path1":"xyz","path2": "xyz2","file1": "filec","file2": "filed","state": "distinct"},
  {"path1":"xyz","path2": "xyz2","file1": "filee","file2": "filef","state": "equal"},
  {"path1":"xyz4","path2": "xyz3","file1": "fileg","file2": "fileh","state": "distinct"}
]`;

// 解析JSON为JS数组
const data = JSON.parse(jsonString);

// 筛选目标对象
const distinctItems = data.filter(item => item.state === 'distinct');

// 转为JSON字符串输出(可选)
const resultJson = JSON.stringify(distinctItems);
console.log(resultJson);

最终输出

执行后得到的结果即为需求中的目标数组:

[{"path1":"xyz","path2":"xyz2","file1":"filec","file2":"filed","state":"distinct"},{"path1":"xyz4","path2":"xyz3","file1":"fileg","file2":"fileh","state":"distinct"}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:05:23