如何使用JavaScript合并數(shù)組中相同ID的對(duì)象并重新組織數(shù)據(jù)格式?

如何使用JavaScript合并數(shù)組中相同ID的對(duì)象并重新組織數(shù)據(jù)格式?

JavaScript數(shù)組對(duì)象合并與數(shù)據(jù)重組

本文演示如何使用JavaScript將數(shù)組中具有相同ID的對(duì)象合并,并將其重新組織成特定格式。 假設(shè)我們有一個(gè)包含ID和其他字段的數(shù)組,需要根據(jù)ID合并這些對(duì)象,并將金額數(shù)據(jù)按照早餐、中餐、晚餐分別映射到新的字段。

原始數(shù)據(jù):

const originalData = [     { id: "202301", jine: 23, type: "晚餐" },     { id: "202301", jine: 87.5, type: "早餐" },     { id: "202301", jine: 1065.5, type: "中餐" },     { id: "202302", jine: 10, type: "晚餐" },     { id: "202302", jine: 181.5, type: "早餐" },     { id: "202302", jine: 633.5, type: "中餐" } ];

目標(biāo)數(shù)據(jù)格式:

const targetDataFormat = [     { id: "202301", jine1: 87.5, jine2: 1065.5, jine3: 23 },     { id: "202302", jine1: 181.5, jine2: 633.5, jine3: 10 } ];

解決方案:

立即學(xué)習(xí)Java免費(fèi)學(xué)習(xí)筆記(深入)”;

我們可以使用reduce方法來(lái)實(shí)現(xiàn)數(shù)據(jù)合并和重組。 reduce方法迭代數(shù)組,并將結(jié)果累積到一個(gè)新的對(duì)象中。

const reorganizedData = originalData.reduce((acc, curr) => {     const existingitem = acc.find(item => item.id === curr.id);     if (existingItem) {         if (curr.type === '早餐') existingItem.jine1 = curr.jine;         if (curr.type === '中餐') existingItem.jine2 = curr.jine;         if (curr.type === '晚餐') existingItem.jine3 = curr.jine;     } else {         const newItem = { id: curr.id };         if (curr.type === '早餐') newItem.jine1 = curr.jine;         if (curr.type === '中餐') newItem.jine2 = curr.jine;         if (curr.type === '晚餐') newItem.jine3 = curr.jine;         acc.push(newItem);     }     return acc; }, []);

這段代碼首先創(chuàng)建一個(gè)空數(shù)組acc作為累加器。 然后,它迭代originalData數(shù)組。 對(duì)于每個(gè)對(duì)象,它檢查累加器中是否已經(jīng)存在具有相同ID的對(duì)象。 如果存在,則根據(jù)type字段更新相應(yīng)的jine字段。 如果不存在,則創(chuàng)建一個(gè)新對(duì)象并將其添加到累加器中。 最終,reorganizedData將包含重組后的數(shù)據(jù)。

這個(gè)方法避免了使用Object.groupBy,直接通過(guò)reduce方法完成數(shù)據(jù)合并和重組,代碼更簡(jiǎn)潔易懂。 最終結(jié)果與目標(biāo)數(shù)據(jù)格式targetDataFormat一致。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊13 分享