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

如何从sections数组中筛选选中的feelings对象并合并为单个数组?

合并选中情感对象为一维数组

问题背景

现有如下结构的sections数组:

const sections = [
    {
        title: "section one",
        expanded: false,
        feelings: [
            {
                title: "Joyful",
                selected: true,
            },
            {
                title: "Happy",
                selected: false,
            },
            {
                title: "Ecstatic",
                selected: true,
            },
        ]
    },
    {
        title: "section two",
        expanded: false,
        feelings: [
            {
                title: "Angry",
                selected: true,
            },
            {
                title: "Mad",
                selected: false,
            },
        ]
    },
]

需要筛选出所有selected为true的feelings对象,合并为一个一维数组,预期结果:

[
    {
      "title": "Joyful",
      "selected": true
    },
    {
      "title": "Ecstatic",
      "selected": true
    },
    {
      "title": "Angry",
      "selected": true
    }
]

原代码使用map返回了嵌套数组,不符合需求:

const selectedFeelings = feelings.map((feeling) => {
    return feeling.sectionFeelings.filter((sectionFeeling) => {
        return sectionFeeling.selected === true;
    });
});

返回结果:

[
  [
    {
      "title": "Joyful",
      "selected": true
    },
    {
      "title": "Ecstatic",
      "selected": true
    }
  ],
  [
    {
      "title": "Angry",
      "selected": true
    },
  ],
]

解决方案

方法1:使用flatMap(推荐)

flatMap会先执行map操作,再将结果扁平化一层,正好解决嵌套数组问题:

const selectedFeelings = sections.flatMap(section => 
  section.feelings.filter(feeling => feeling.selected === true)
);

方法2:map + flat()

对原map的结果调用flat()方法,将嵌套数组转为一维:

const selectedFeelings = sections
  .map(section => section.feelings.filter(feeling => feeling.selected))
  .flat();

方法3:使用reduce手动累加

通过reduce遍历每个section,将符合条件的feelings逐个添加到结果数组中:

const selectedFeelings = sections.reduce((acc, section) => {
  const filtered = section.feelings.filter(feeling => feeling.selected);
  return acc.concat(filtered);
}, []);

以上三种方法都能得到预期的一维数组结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:45:32