I have a groupedBy subscription lodash array, and I want to sum the quantity property and return the value.
Example
{
sub_1MT4LuP6DArCazGmEdJd: [
{
id: 'prod_HleWjM6culM',
quantity: 1,
},
{
id: 'prod_HleWjM6culM',
quantity: 3,
}
]
}
The output should be:
{
sub_1MT4LuP6DArCazGmEdJd: [
{
totalQuantity: 4,
},
]
}
Which is the best way to do this sum of values in a lodash grouped array?
You can use _.sumBy
.
let o = { sub_1MT4LuP6DArCazGmEdJd: [ { id: 'prod_HleWjM6culM', quantity: 1, }, { id: 'prod_HleWjM6culM', quantity: 3, } ] }; o.sub_1MT4LuP6DArCazGmEdJd = [{totalQuantity: _.sumBy(o.sub_1MT4LuP6DArCazGmEdJd, 'quantity')}]; console.log(o);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/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.