如何将线性对象数组转换为结构化分组的对象数组
如何将指定对象数组转换为目标结构?
原输入数组
let data = [ { text: 'label' }, { text: 'username' }, { text: 'category' }, { text: 'book' }, { text: 'john' }, { text: 'education' }, { text: 'car' }, { text: 'doe' }, { text: 'automotive' }, { text: 'shoes' }, { text: 'cena' }, { text: 'fashion' }, ]
期望输出数组
let result = [ { label: 'book', username: 'john', category: 'education' }, { label: 'car', username: 'doe', category: 'automotive' }, { label: 'shoes', username: 'cena', category: 'fashion' }, ]
实现方法
核心逻辑是:先提取前三个元素作为目标对象的键名,再将后续元素按每3个一组拆分,每组元素依次对应键名生成新对象。
方法一:基础循环实现
const data = [/* 原输入数组 */]; // 提取目标对象的键名 const keys = data.slice(0, 3).map(item => item.text); // 提取所有需要作为值的文本 const valueTexts = data.slice(3).map(item => item.text); const result = []; // 每3个值为一组,生成对应对象 for (let i = 0; i < valueTexts.length; i += 3) { const currentGroup = valueTexts.slice(i, i + 3); const newObj = {}; // 将键名和对应组的值绑定 keys.forEach((key, idx) => { newObj[key] = currentGroup[idx]; }); result.push(newObj); }
方法二:使用reduce简化代码
const data = [/* 原输入数组 */]; // 提取键名 const keys = data.slice(0, 3).map(item => item.text); const result = data.slice(3) .map(item => item.text) .reduce((acc, curr, index) => { // 计算当前值属于第几组 const groupIndex = Math.floor(index / 3); // 如果该组对象不存在则初始化 if (!acc[groupIndex]) { acc[groupIndex] = {}; } // 将当前值对应到组内的键名 acc[groupIndex][keys[index % 3]] = curr; return acc; }, []);
两种方法最终都能得到你期望的结果数组,可根据代码风格偏好选择。
内容的提问来源于stack exchange,提问作者noobier43
相关产品推荐
相关产品推荐

