I have a problem with filtering an array with nested objects.
[{
"firstName": "Kevin",
"lastName": "Smith",
"expenses": {
"drink1": 25,
"drink2": 20
}
},
{
"firstName": "John",
"lastName": "Rambo",
"expenses": {
"coffe": 10,
"cake": 20
}
}
]
I want to get the objects where the sum of all expenses is > 35. How to get inside expenses
? Or maybe filter is not a proper way here.
Just filter
it, with a condition using reduce
to sum the expenses! Pretty straight forward :)
const input = [{
"firstName": "Kevin",
"lastName": "Smith",
"expenses": {
"drink1": 26,
"drink2": 20
}
},
{
"firstName": "John",
"lastName": "Rambo",
"expenses": {
"coffe": 10,
"cake": 20
}
}
];
const output = input.filter(user => Object.values(user.expenses).reduce((acc, expense) => acc + expense) > 45);
console.log(output);
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