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
}]
}]
我想使用 loadash 如何深度求和来对 item_price
以及 "ingredients":[{"price":3}]
求和
我尝试了 item_price
_.sumBy(data, 'item_price')
这样可以得到数组中元素价格的总价,但是如何获取配料和item_price的价格总和
最佳答案
元素总和与成分价格
除了将属性名称作为字符串传递给 _sumBy
函数,您还可以传递一个函数,该函数确定应用哪些函数来获取可以求和的值。因此我们可以将查询替换为:
_.sumBy(data, <b>x => x.item_price</b>)
但现在我们还需要总结一下要素。我们将如何做到这一点?当然使用另一个 _.sumBy
!
_.sumBy(data, x => x.item_price + <b>_.sumBy(x.ingredients, 'price')</b>)
(这会产生 53
)。
乘以数量
我们也可以立即将这些值与 quantity
属性相乘:
_.sumBy(data, x => <b>x.quantity * (</b>x.item_price + _.sumBy(x.ingredients, 'price')<b>)</b>)
(这再次产生 53
,因为所有数量都是 1)。
关于javascript - 如何使用lodash深度_sum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47671345/