Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering array with objects inside an object

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.

like image 983
Kamil Staszewski Avatar asked Nov 07 '18 18:11

Kamil Staszewski


1 Answers

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);
like image 192
sjahan Avatar answered Sep 18 '22 15:09

sjahan