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

如何在Javascript中合并嵌套数组的data子数组

如何合并数组中每个元素的data子数组为单个数组?

你可以用以下几种JavaScript方法实现需求:

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

flatMap()先对数组每个元素执行映射操作,再将结果扁平化一层,完美适配你的场景:

const originalArray = [
    {
        "title": "Javascript 1",
        "data": [
            { "text": "hello world 1" },
            { "text": "hello world 2" }
        ]
    },
    {
        "title": "Javascript 2",
        "data": [
            { "text": "hello world 3" },
            { "text": "hello world 4" }
        ]
    }
];

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

运行后即可得到你期望的合并数组。

方法2:使用reduce()

如果需要额外逻辑(比如过滤空的data数组),reduce()能提供更灵活的控制:

const mergedArray = originalArray.reduce((accumulator, currentItem) => {
    // 可选:跳过data为空的元素
    if (currentItem.data?.length) {
        accumulator.push(...currentItem.data);
    }
    return accumulator;
}, []);

方法3:传统for循环

若需兼容老旧JavaScript环境,普通循环是稳妥的选择:

const mergedArray = [];
for (let i = 0; i < originalArray.length; i++) {
    const dataItems = originalArray[i].data;
    for (let j = 0; j < dataItems.length; j++) {
        mergedArray.push(dataItems[j]);
    }
}

以上三种方法都能达成目标,优先推荐flatMap(),代码简洁且可读性强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:35:40