我有以下包含对象的数组,我想总结所有出现的 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>
如您所见,我得到了
0
的数组。值(value)观。但是,我想取回 377
的结果值.有什么建议我做错了吗?感谢您的回复!
最佳答案
使用纯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>
关于javascript - 用对象求和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670204/