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

如何将JavaScript中map嵌套遍历的结果合并为单一数组?

如何将嵌套数组合并为单一数组?

原始代码

const data = {
  data: [
    {
      entry: [
        {
          id: 1,
          title: "hello",
        },
        {
          id: 2,
          title: "hi",
        },
      ],
    },
    {
      entry: [
        {
          id: 3,
          title: "hola",
        },
        {
          id: 4,
          title: "hey",
        },
      ],
    },
  ],
};
let rec = data.data.map((d) => {
  return d.entry.map((reco) => {
    return console.log(reco);
  });
});

需求

需要将嵌套的entry数组合并为如下格式的单一数组:

[{id:1 , title: "hello"} ,{id:2 , title: "hi"} , {id:3 , title: "hola"} ,{id:4 , title: "hey"} ]

解决方案

方法1:使用flatMap(最简洁)

flatMap会先对数组元素执行map操作,再将结果扁平化为一维数组,正好适配当前的嵌套结构:

const mergedArray = data.data.flatMap(item => item.entry);
console.log(mergedArray);

方法2:使用map + flat

先通过map提取所有entry数组得到二维数组,再用flat()将其扁平为一维数组(默认只扁平一层,完全满足需求):

const mergedArray = data.data.map(item => item.entry).flat();

方法3:使用reduce

通过reduce手动累加数组,每次将当前元素的entry数组合并到累加器中:

const mergedArray = data.data.reduce((acc, item) => {
  return acc.concat(item.entry);
}, []);

关于你之前尝试失败的可能原因

  • 使用reduce时可能未正确返回累加器(比如漏掉return语句)
  • 使用flat时可能错误设置了扁平层数(当前结构只需要扁平一层,无需用flat(Infinity))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:33:16