如何将嵌套的含对象数组合并为单一对象数组?
嵌套数组合并为单层数组的实现方案
给定嵌套数组:
const nestedArray = [ [ { "item1": "text", "item2": 1 }, { "item1": "text", "item2": 2 } ], [ { "item1": "text", "item2": 3 } ], [ { "item1": "text", "item2": 4 }, { "item1": "text", "item2": 5 }, { "item1": "text", "item2": 6 } ] ];
要将所有子数组中的对象合并为单层数组,这里提供几种实用的实现方式:
方法1:使用Array.prototype.flat()
这是最简洁的方案,flat()默认仅展开一层嵌套,完全匹配你的场景:
const mergedArray = nestedArray.flat();
如果是更深层级的嵌套,可以传入参数(比如flat(Infinity)展开所有层级),你的场景用无参即可。
方法2:扩展运算符配合concat()
利用concat()可接收多数组参数的特性,用扩展运算符展开嵌套数组的子元素:
const mergedArray = [].concat(...nestedArray);
方法3:reduce()遍历累加
通过reduce()逐个合并子数组元素:
const mergedArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
以上三种方法最终都会得到目标结果:
[ { "item1": "text", "item2": 1 }, { "item1": "text", "item2": 2 }, { "item1": "text", "item2": 3 }, { "item1": "text", "item2": 4 }, { "item1": "text", "item2": 5 }, { "item1": "text", "item2": 6 } ]
内容的提问来源于stack exchange,提问作者Spawnet
相关产品推荐
相关产品推荐

