如何在JavaScript中筛选JSON文件里state为distinct的对象?
在JavaScript中提取state为
distinct的JSON对象 实现步骤
- 修正JSON格式(若为字符串形式):标准JSON要求属性名必须用双引号包裹,先调整你的JSON字符串使其符合规范。
- 解析JSON(若为字符串):用
JSON.parse()将JSON字符串转换为JavaScript数组。 - 筛选目标对象:利用数组的
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
相关产品推荐
相关产品推荐

