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

JSON数组双重过滤失效求助附代码示例

解决JSON数组过滤问题

嘿,我来帮你搞定这个数组过滤的需求!看起来你是想保留外层每个对象的data字段,同时把内部dataArray里status为false的元素剔除掉,对吧?

解决方案:用map+filter组合处理

我们可以通过JavaScript的map遍历外层数组,再用filter筛选内部数组的符合条件项,这样既能保留原结构,又能得到过滤后的结果:

var all = [
  {
    data : "test1",
    dataArray : [
      { name : "abc", status : true, address: "test" },
      { name : "xyz", status : false, address: "test" },
      { name : "pqr", status : true, address: "test" },
    ]
  },
  {
    data : "test2",
    dataArray : [
      { name : "abc", status : true, address: "test" },
      { name : "xyz", status : false, address: "test" },
      { name : "pqr", status : false, address: "test" },
    ]
  }
];

// 生成新的过滤后数组(不修改原数组)
const filteredAll = all.map(item => ({
  ...item, // 保留原对象的所有属性(这里就是data字段)
  dataArray: item.dataArray.filter(subItem => subItem.status === true)
}));

console.log(filteredAll);

预期输出

运行后filteredAll的结构会是这样:

[
  {
    "data": "test1",
    "dataArray": [
      { "name": "abc", "status": true, "address": "test" },
      { "name": "pqr", "status": true, "address": "test" }
    ]
  },
  {
    "data": "test2",
    "dataArray": [
      { "name": "abc", "status": true, "address": "test" }
    ]
  }
]

如果想直接修改原数组

要是你不需要保留原数组,想直接修改它,可以用forEach替代map:

all.forEach(item => {
  item.dataArray = item.dataArray.filter(subItem => subItem.status === true);
});

这样处理后,原all数组的dataArray就直接被过滤后的结果替换啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:07:09