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

如何从对象数组中提取所有groups子数组元素并合并为新数组?

如何从对象数组中提取并合并所有嵌套的groups数组对象?

你当前代码里用find方法只能拿到第一个包含groups属性的对象,无法实现合并所有嵌套groups数组的需求。可以通过以下两种方式实现目标:

方法一:使用flatMap(简洁推荐)

flatMap可以先映射每个元素的groups,再自动扁平化数组,同时过滤掉非数组类型的groups:

const GroupData = mydata.flatMap(item => {
  // 仅当groups是数组时返回其内容,否则返回空数组
  return Array.isArray(item.groups) ? item.groups : [];
});

方法二:使用reduce(兼容性更广)

如果需要兼容不支持flatMap的环境,可以用reduce手动累加:

const GroupData = mydata.reduce((result, item) => {
  // 判断groups是否为数组,是的话就展开添加到结果数组
  if (Array.isArray(item.groups)) {
    result.push(...item.groups);
  }
  return result;
}, []);

执行上述代码后,GroupData就会得到你期望的结果:

[ { id: "679d8044", name: "group 3" }, { id: "b9342eb8", name: "group 1" } ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:05:18