合并对象并对 JavaScript 中的单个属性进行求和
假设我们有两个对象数组,这些数组包含有关某公司一些产品的信息 -
const first = [ { id: "57e7a1cd6a3f3669dc03db58", quantity:3 }, { id: "57e77b06e0566d496b51fed5", quantity:3 }, { id: "57e7a1cd6a3f3669dc03db58", quantity:3 }, { id: "57e77b06e0566d496b51fed5", quantity:3 } ]; const second = [ { id: "57e7a1cd6a3f3669dc03db58", quantity:6 }, { id: "57e77b06e0566d496b51fed5", quantity:6 } ];
我们现在需要编写一个函数,该函数合并这两个数组,使得具有相同 id 的对象不会重复出现,而且重复 id 的对象的 quantity 属性会加在一起。
因此,让我们编写此函数的代码 -
示例
const first = [ { id: "57e7a1cd6a3f3669dc03db58", quantity:3 }, { id: "57e77b06e0566d496b51fed5", quantity:3 }, { id: "57e7a1cd6a3f3669dc03db58", quantity:3 }, { id: "57e77b06e0566d496b51fed5", quantity:3 } ]; const second = [ { id: "57e7a1cd6a3f3669dc03db58", quantity:6 }, { id: "57e77b06e0566d496b51fed5", quantity:6 } ]; const mergeArray = (first, second) => { return [...first, ...second].reduce((acc, val, i, arr) => { const { id, quantity } = val; const ind = acc.findIndex(el => el.id === id); if(ind !== -1){ acc[ind].quantity += quantity; }else{ acc.push({ id, quantity }); } return acc; }, []); } console.log(mergeArray(first, second));
输出
控制台中的输出将是 -
[ { id: '57e7a1cd6a3f3669dc03db58', quantity: 12 }, { id: '57e77b06e0566d496b51fed5', quantity: 12 } ]
广告