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

如何用数组元素过滤对象数组并保持一维结构?

问题:基于指定数组过滤对象数组,输出一维结果

现有待过滤的对象数组:

const data = [
  {id: 1, method: "bike"},
  {id: 2, method: "walk"},
  {id: 3, method: "bus"},
  {id: 4, method: "bike"},
  {id: 5, method: "walk"},
  {id: 5, method: "bus"},
]

提供三个可选的过滤数组(需保留对应method值的对象):

const filter1 = ['bike'];
const filter2 = ['bike', 'walk'];
const filter3 = ['bike', 'walk', 'bus'];

当前实现会生成二维数组,代码如下:

let output = [];
const filterArr = filter2.forEach(element => {
 const filt = data.filter(el => el.method === element);
 output.push(filt);
});

期望输出与原数组结构一致的一维数组(以filter2为例):

const want = [
    {id: 1, method: "bike"},
    {id: 2, method: "walk"},
    {id: 4, method: "bike"},
    {id: 5, method: "walk"},
]

解决方案

方法一:直接过滤(推荐)

无需嵌套循环,一次过滤即可完成,代码简洁高效:

const targetFilter = filter2;
const output = data.filter(item => targetFilter.includes(item.method));

方法二:修复原有代码

原代码因直接推入数组导致二维结构,可通过扩展运算符或concat将元素逐个合并:

let output = [];
filter2.forEach(element => {
 const filt = data.filter(el => el.method === element);
 // 用扩展运算符展开数组,推入单个元素
 output.push(...filt);
});

或使用concat合并:

let output = [];
filter2.forEach(element => {
 const filt = data.filter(el => el.method === element);
 output = output.concat(filt);
});

方法三:使用flatMap

利用flatMap自动扁平化嵌套数组的特性,一步得到结果:

const output = filter2.flatMap(element => 
  data.filter(el => el.method === element)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:10:16