This question already has answers here:
How to merge two arrays and sum values of duplicate objects using lodash

(5个答案)


3个月前关闭。




我有两个对象的数组,原始对象和选定对象,如下所示:
original =[{ id: 4 , quantity: 4 },{ id: 2 , quantity: 2 },{ id: 76 , quantity: 2 }]
selected = [{ id: 2 , quantity: 1 }, { id: 100 , quantity: 7 }]
我希望能够合并ID上的那些数组,如果它们具有相似的ID,我应该总结数量,
在这种情况下,结果数组应如下所示:
result=[{ id: 4 , quantity: 4 },{ id: 2 , quantity: 3 },{ id: 76 , quantity: 2 } , { id: 100 , quantity: 7 }]
我想到做这样的事情:
 const result =original.map(o => ({
            ...selectedArray.findIndex((s) => {(s.id === o.id) && selected)? return }
            ...original
         }));
但是我不确定应该如何增加数量,需要帮助的任何帮助或资源将不胜感激。

最佳答案

您可以找到该对象并更新quantity或推送一个新对象。

const
    original = [{ id: 4, quantity: 4 }, { id: 2, quantity: 2 }, { id: 76, quantity: 2 }],
    selected = [{ id: 2, quantity: 1 }, { id: 100, quantity: 7 }],
    merged = [...original, ...selected].reduce((r, { id, quantity }) => {
        const item = r.find(q => q.id === id);
        if (item) item.quantity += quantity;
        else r.push({ id, quantity });
        return r;
    }, []);

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }

具有哈希表的解决方案。

const
    mergeTo = (target, reference = {}) => ({ id, quantity }) => {
        if (reference[id]) reference[id].quantity += quantity;
        else target.push(reference[id] = { id, quantity });
    },
    original = [{ id: 4, quantity: 4 }, { id: 2, quantity: 2 }, { id: 76, quantity: 2 }],
    selected = [{ id: 2, quantity: 1 }, { id: 100, quantity: 7 }],
    merged = [],
    merge = mergeTo(merged);


original.forEach(merge);
selected.forEach(merge);

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }

10-05 20:52
查看更多