JavaScript中扁平化嵌套数组:移除冗余分组数组
扁平化嵌套数组,移除冗余分组
现有一段嵌套数组代码,其中的内层分组属于冗余分隔,实际没有用途,需要将其扁平化,把所有对象合并到一个单层数组中:
原代码:
const header = [ [ { id: "1", text: "A", }, ], [ { id: "2", text: "B", array:[1,2,3], }, { id: "2", text: "B1", }, ], [ { id: "3", text: "A", }, ], ];
期望得到的单层数组结果:
const header = [ { id: "1", text: "A", }, { id: "2", text: "B", array:[1,2,3], }, { id: "2", text: "B1", }, { id: "3", text: "A", }, ];
实现方案
- 简洁实现(ES2019+):直接使用数组的
flat()方法,它默认会展开一层嵌套数组,刚好匹配需求:
// 生成新的扁平化数组 const flattenedHeader = header.flat(); // 或者直接替换原变量 header = header.flat();
- 兼容旧环境实现:如果需要支持不具备
flat()方法的旧环境,可以用reduce结合concat手动合并:
const flattenedHeader = header.reduce((result, currentGroup) => { return result.concat(currentGroup); }, []);
两种方法都会将原数组中每个内层分组里的对象全部提取出来,合并成一个单层数组,完全达到期望效果。
内容的提问来源于stack exchange,提问作者Mimu
相关产品推荐
相关产品推荐

