简体   繁体   中英

how to deep _sumBy using lodash?

var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }]

i want to sum the item_price as well as "ingredients":[{"price":3}] using loadash how to deep sumBy

i tryed item_price

_.sumBy(data, 'item_price')

this can get the total price of item price in an array, but how to get sum of price of ingredients and item_price

Sum of elements with the price of the ingredients

Besides passing the name of an attribute as a string to the _sumBy function, you can also pass a function that determines what function to apply the items to obtain values that can be summed up. So we can replace the query with:

_.sumBy(data, )

But now we still need to sum up the ingredients. How will we do that? Use another _.sumBy of course!

_.sumBy(data, x => x.item_price + )

(this yields 53 ).

Multiply with the quantity

We can immediately multiply these values with the quantity attribute as well:

_.sumBy(data, x => x.item_price + _.sumBy(x.ingredients, 'price'))

(this yields again 53 , since all quantities are 1).

Lodash#SumBy can take a function as second argument. You can use it to access the ingredients of each items and use SumBy once again.

 const data = [{ item_name: 'Jumbo Combo', item_price: 25, item_key: '9lazhy15tp2fgo72', quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}, { item_name: 'Swiss & Mushroom Combo', item_key: 'e1vdfos6s50d5kej', item_price: 22, quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}]; const sum = _.sumBy(data, item => item.item_price + _.sumBy(item.ingredients, 'price')); console.log(sum); 
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script> 

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