如何将JS二维结构拆分为N个数组?附一维数组拆分实现
如何将JS中键对应数组的对象转换为对象数组
输入输出示例
输入对象(每个键对应一个同长度的数组):
const input = { name: ['name1', 'name2', 'name3', 'name4'], price: ['price1', 'price2', 'price3', 'price4'] };
期望得到的对象数组(按索引对齐键值):
[ {name: 'name1', price: 'price1'}, {name: 'name2', price: 'price2'}, {name: 'name3', price: 'price3'}, {name: 'name4', price: 'price4'} ]
几种实现方案
1. 通用型for循环(适配任意键名)
如果不确定对象里有多少个键,或者后续可能新增字段,用这个方法最稳妥:
function transformToObjectArray(input) { // 获取所有键名,比如['name', 'price'] const keys = Object.keys(input); // 以第一个数组的长度作为遍历次数(假设所有数组长度一致) const itemCount = input[keys[0]].length; const result = []; for (let i = 0; i < itemCount; i++) { const newObj = {}; // 遍历每个键,把对应索引的值赋值给新对象 keys.forEach(key => { newObj[key] = input[key][i]; }); result.push(newObj); } return result; } // 使用示例 const output = transformToObjectArray(input); console.log(output);
2. 简洁map写法(已知固定键名)
如果已经明确知道对象的键名(比如只有name和price),可以用map直接生成,代码更短:
const output = input.name.map((nameVal, index) => ({ name: nameVal, price: input.price[index] }));
3. 用reduce实现通用转换
和for循环逻辑类似,只是用reduce替代外层循环,风格更函数式:
function transformToObjectArray(input) { const keys = Object.keys(input); return input[keys[0]].reduce((resultArr, _, index) => { const obj = keys.reduce((currentObj, key) => { currentObj[key] = input[key][index]; return currentObj; }, {}); resultArr.push(obj); return resultArr; }, []); }
和你之前的一维chunk函数的区别
你写的chunk函数是把单个一维数组拆分成指定大小的子数组,核心是“拆分单个数组”;而当前需求是把多个同长度数组按索引一一对应,组合成对象数组,核心是“索引对齐合并”,逻辑完全不同。
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

