简体   繁体   中英

How to Merge Matching key values in Array or Objects

What do I have wrong here? Please feel free to critisise and shame my question formatting, I'm trying to learn how best to ask these questions.

Eg

{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}

Thanks to the Reactiflux discord community, this was the solution to my problem of reducing values.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM