如何在JavaScript中按invoice_nr合并对象为嵌套数组?
JavaScript按
invoice_nr合并对象到子数组的实现方法 给定如下输入数组:
const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ];
需要将拥有相同invoice_nr的对象合并到同一个子数组中,最终得到嵌套数组结构如下:
const mergedResult = [ [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' } ], [ { invoice_nr: 17, order_id: 5574, color: 'green' } ], [ { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ] ];
以下是几种实用的实现方式:
方法一:reduce分组 + Object.values提取
这是最简洁高效的写法,先用reduce把数据按invoice_nr分组到对象中,再提取对象的所有值得到目标数组:
const mergedResult = Object.values( result.reduce((acc, item) => { const key = item.invoice_nr; acc[key] = acc[key] || []; acc[key].push(item); return acc; }, {}) ); console.log(mergedResult);
方法二:Map结构分组
用ES6的Map来存储分组关系,键为invoice_nr,值为对应子数组,最后把Map的values转为数组:
const groupMap = new Map(); result.forEach(item => { const key = item.invoice_nr; if (!groupMap.has(key)) { groupMap.set(key, []); } groupMap.get(key).push(item); }); const mergedResult = Array.from(groupMap.values()); console.log(mergedResult);
方法三:手动遍历查找(新手友好)
如果对高阶函数不太熟悉,可以用基础循环手动处理,每次查找已有分组是否匹配当前invoice_nr,不匹配就新建子数组:
const mergedResult = []; result.forEach(item => { // 查找是否存在对应invoice_nr的子数组 const existingGroup = mergedResult.find(group => group[0].invoice_nr === item.invoice_nr); if (existingGroup) { existingGroup.push(item); } else { mergedResult.push([item]); } }); console.log(mergedResult);
内容的提问来源于stack exchange,提问作者Samir Quluzadeh
相关产品推荐
相关产品推荐

