如何将二维数组同位置元素重组为以索引为键的对象?
解决二维数组转按列索引为键的对象问题
要实现把二维数组转换为键是列索引、值为对应列所有元素的数组的对象,这里提供几种简洁的JavaScript实现方式:
方法一:使用Array.prototype.reduce结合forEach
遍历原数组的每一行,再遍历行内每个元素,按列索引将元素归类到结果对象中:
const arr = [ [0, 2, 5], [19, 4, 7], [98, 12, 3] ]; const result = arr.reduce((acc, row) => { row.forEach((val, colIndex) => { if (!acc[colIndex]) { acc[colIndex] = []; } acc[colIndex].push(val); }); return acc; }, {}); console.log(result); // 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 7, 3] }
方法二:先确定最大列数,再逐列提取
如果数组中行的长度不一致,可先获取最长行的列数,再循环每一列收集元素(自动忽略行中不存在的列元素):
const arr = [ [0, 2, 5], [19, 4], [98, 12, 3, 8] ]; // 获取最长行的列数 const maxCols = Math.max(...arr.map(row => row.length)); const result = {}; for (let col = 0; col < maxCols; col++) { result[col] = arr.map(row => row[col]).filter(val => val !== undefined); } console.log(result); // 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 3], 3: [8] }
方法三:使用Object.fromEntries(ES2019+)
若环境支持ES2019及以上,可结合Object.fromEntries简化代码,同样基于最大列数处理:
const arr = [ [0, 2, 5], [19, 4, 7], [98, 12, 3] ]; const maxCols = Math.max(...arr.map(row => row.length)); const result = Object.fromEntries( Array.from({ length: maxCols }, (_, col) => [ col, arr.map(row => row[col]).filter(val => val !== undefined) ]) ); console.log(result); // 输出:{ 0: [0, 19, 98], 1: [2, 4, 12], 2: [5, 7, 3] }
可根据数组结构和运行环境选择合适的实现方式。
内容的提问来源于stack exchange,提问作者blackratio
相关产品推荐
相关产品推荐

