如何在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
相关产品推荐
相关产品推荐

