Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the value of objects and calculate them?

Tags:

javascript

I can't figure out how can I extract the value of an attribute in my objects and then calculate them.

So I have as follow:

const data = [
   {
      topUp: true, value: 200
   },
   {
      topUp: true, value: 18
   },
   {
      topUp: false, value: 20
   },
   {
      topUp: true, value: 100
   },
]

const totalSpending = data.filter(
   transaction => transaction.topUp == true
);

Now I should get 3 objects. From here I want to get the value of each one like [200, 18, 100] and add them together so my const totalSpending will be 318.

like image 209
Markus Hayner Avatar asked Mar 05 '19 13:03

Markus Hayner


People also ask

How do you extract a value from an object in Python?

Python getattr() function. Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned.


2 Answers

You can achieve this relatively easily using reduce, the conditional operator and destructuring assignment:

const data = [{topUp: true, value: 200}, {topUp: true, value: 18}, {topUp: false, value: 20}, {topUp: true, value: 100}],

res = data.reduce((acc, {topUp, value}) => topUp ? acc + value : acc, 0);
console.log(res);

The above will get the properties topUp and value, and then add value to the accumulator (ie the total sum) if topUp is true, if it is false, it will return acc (and thus won't add to the sum).

Alternatively, you can remove the ternary and use math with booleans:

const data = [{topUp: true, value: 200}, {topUp: true, value: 18}, {topUp: false, value: 20}, {topUp: true, value: 100}],

res = data.reduce((acc, {topUp, value}) => acc + value*topUp, 0);
console.log(res);
like image 194
Nick Parsons Avatar answered Oct 19 '22 17:10

Nick Parsons


You can use reduce also that is a higher order function available on arrays which will filter out the values as well as add them.

const data = [{
    topUp: true,
    value: 200
  },
  {
    topUp: true,
    value: 18
  },
  {
    topUp: false,
    value: 20
  },
  {
    topUp: true,
    value: 100
  },
]

const totalSpending = data.reduce((aggregator, obj) => {
  return obj.topUp ? aggregator + obj.value : aggregator
}, 0)

console.log(totalSpending)
like image 34
Hemant Parashar Avatar answered Oct 19 '22 17:10

Hemant Parashar