Filtering array with objects inside an object

  • A+
Category:Languages

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);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: