问题
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!
回答1:
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>
回答2:
I've read the answers, but I'd like to add an explanation to your problem. The reason you're getting an array is because of using .map. As map returns you the array not a single element. Moreover, you are expecting to get the returned array as modified and map doesn't do that.
What you're trying to achieve is can be done using .reduce. I mean that's why .reduce is there
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
}
];
var getWatt = allProducts.reduce((acc,curr)=> acc + curr.watt,0);
console.log(getWatt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
回答3:
Try the following:
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
}
];
var sum = allProducts.reduce((sum,a)=>{
return sum + a.watt;
},0);
console.log(sum);
回答4:
Just take a single _.sumBy with the array of objects and the wanted key watt for summing.
Your attempt uses an object, instead of an array for _.sumBy. The object is not an array and the return value is zero.
var 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 }],
getWatt = _.sumBy(allProducts, 'watt');
console.log(getWatt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
来源:https://stackoverflow.com/questions/50670204/sum-up-array-with-objects