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

如何用array.filter和includes过滤含嵌套数组属性的数组数据

根据嵌套数组中的ID过滤数据

假设你的数据源如下(修正了JSON的引号格式,JSON规范要求字符串使用双引号):

[
  {
    "id": 1,
    "name": "name1",
    "array": [{"id": 1}, {"id": 2}]
  },
  {
    "id": 2,
    "name": "name2",
    "array": [{"id": 3}, {"id": 4}]
  },
  {
    "id": 3,
    "name": "name3",
    "array": [{"id": 2}, {"id": 5}]
  }
]

要根据array中包含的ID过滤外层数组,你可以结合Array.filter()、Array.map()和Array.includes()实现,具体方案如下:

1. 过滤单个目标ID

比如要筛选出array中包含id=2的外层元素:

const data = [
  { "id": 1, "name": "name1", "array": [{"id": 1}, {"id": 2}] },
  { "id": 2, "name": "name2", "array": [{"id": 3}, {"id": 4}] },
  { "id": 3, "name": "name3", "array": [{"id": 2}, {"id": 5}] }
];

const targetId = 2;
const filteredData = data.filter(item => {
  // 提取内层array的所有id,生成纯id数组
  const innerIds = item.array.map(obj => obj.id);
  // 检查目标id是否在这个数组里
  return innerIds.includes(targetId);
});

console.log(filteredData);
// 输出结果:
// [
//   { "id": 1, "name": "name1", "array": [{"id": 1}, {"id": 2}] },
//   { "id": 3, "name": "name3", "array": [{"id": 2}, {"id": 5}] }
// ]

2. 过滤多个目标ID

如果需要筛选array中包含任意一个目标ID的元素,可以把目标ID放在数组里,结合some()和includes():

const targetIds = [2, 3];
const filteredData = data.filter(item => {
  const innerIds = item.array.map(obj => obj.id);
  // 检查innerIds是否和targetIds有交集
  return targetIds.some(id => innerIds.includes(id));
});

console.log(filteredData);
// 输出结果:
// [
//   { "id": 1, "name": "name1", "array": [{"id": 1}, {"id": 2}] },
//   { "id": 2, "name": "name2", "array": [{"id": 3}, {"id": 4}] },
//   { "id": 3, "name": "name3", "array": [{"id": 2}, {"id": 5}] }
// ]

关键说明

  • filter():遍历外层数组,仅保留返回true的元素
  • map():将内层array的对象转换为纯ID数组,让includes()可以直接做值匹配
  • includes():判断目标ID是否存在于纯ID数组中,返回布尔值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:10:03