I am having the following array with objects and I would like to sum up all occurrences of watt
:
let allProducts = [{
"unique_id": "102",
"currency": "$",
"price": "529.99",
"watt": 150
},
{
"unique_id": "11",
"currency": "$",
"price": "323",
"watt": 150
},
{
"unique_id": "13",
"currency": "$",
"price": "23",
"watt": 77
}
]
let getWatt =
_(allProducts)
.map((objs, key) => ({
'watt': _.sumBy(objs, 'watt')
}))
.value()
console.log(getWatt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
As you can see I get back an array of 0
values. However, I would like to get back the result value of 377
. Any suggestions what I am doing wrong?
I appreciate your replies!
It's easy using plain js
const sum = allProducts.reduce((a, {watt}) => a + watt, 0);
console.log(sum);
<script>
let allProducts = [{
"unique_id": "102",
"currency": "$",
"price": "529.99",
"watt": 150
},
{
"unique_id": "11",
"currency": "$",
"price": "323",
"watt": 150
},
{
"unique_id": "13",
"currency": "$",
"price": "23",
"watt": 77
}
]
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With