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

JavaScript嵌套数组过滤:保留slides中指定name元素并重组

JavaScript嵌套数组过滤解决方案

给定如下嵌套结构的数组:

const slides = [
    {title: 'one', status: 1, slides: [
        {name: 'first', id: 1},
        {name: 'second', id: 2},
        {name: 'third', id: 3},
        {name: 'fourth', id: 4},
    ]},
    {title: 'two', status: 1, slides: [
        {name: 'all', id: 1}
    ]},
]

需要过滤每个对象中嵌套的slides数组,仅保留name字段为'first'或'all'的元素,生成新数组。可以通过map结合filter实现,代码如下:

const allowedNames = new Set(['first', 'all']);
const filteredSlides = slides.map(item => ({
  ...item,
  slides: item.slides.filter(slide => allowedNames.has(slide.name))
}));

console.log(filteredSlides);

代码说明

  • 用Set存储允许的名称,提升查询效率
  • map遍历外层数组,对每个元素创建新对象(避免修改原数组)
  • 解构原对象的所有属性,再重新赋值slides字段,用filter筛选出符合条件的嵌套元素

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

const slides = [
    {title: 'one', status: 1, slides: [
        {name: 'first', id: 1},
    ]},
    {title: 'two', status: 1, slides: [
        {name: 'all', id: 1}
    ]},
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:57:02