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.
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.
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With