Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up array with objects

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!

like image 210
Carol.Kar Avatar asked Nov 29 '22 08:11

Carol.Kar


1 Answers

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>
like image 190
baao Avatar answered Dec 09 '22 19:12

baao