簡體   English   中英

如何合並數組或對象中的匹配鍵值

[英]How to Merge Matching key values in Array or Objects

我在這里有什么問題? 請隨時批評和羞辱我的問題格式,我正在努力學習如何最好地提出這些問題。

例如

{sellerID1: 26.52, sellerID1: 12.46, sellerID2: 72.39}

const cartItems = [{
        "oq23jnq89vj3": {
            sellerID: "aj8f9b73h2v37fy",
            productPrice: 3.99
        }
    },
    {
        "p98nq4hn984t": {
            sellerID: "aj8f9b73h2v37fy",
            productPrice: 19.99
        }
    },
    {
        "vzly89nvhj08": {
            sellerID: "zwlvin3u598n84w",
            productPrice: 10.00
        }
    }
]
for (const item in cartItems) {
    const sellerTotals = {}
    const sellerIDs = {}
    const productPrice = {}
    sellerIDs.push[item.sellerID]
    productPrice.push[item.productPrice]
    const sellerTotals = [...SellerIDs, ...productPrice] where SellerIDs "=="
    SellerIDs
}
console.log(sellerTotals)
// Desired return { sellerID1: 23.98, sellerID2: 10.00}

感謝 Reactiflux discord 社區,這是我reducing值問題的解決方案。

cartItems.reduce((acc, value) => {
        if(acc[value.productSellerUserID]) {
          acc[value.productSellerUserID] += Number(value.productPrice);
        } else {
          acc[value.productSellerUserID] = Number(value.productPrice);
        }
        return acc;
    }, {}),
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM