Tax Raoul
Tax Raoul

Reputation: 73

Javascript or lodash : filter an array of objects with value of a nested array

I have an array of Users as below (I have shortened it):

 [
  {
    "displayName": "Alaotra",
    "districts": [
      {
        "regions_id_region": "11",            
        "id_district": "102"
      },
      {           
        "regions_id_region": "11",            
        "id_district": "101",          
      }
    ]
  },
  {
    "displayName": "Alexandre",
    "districts": [
      {
        "regions_id_region": "42",
        "id_district": "411",           
      },
      {           
        "id_district": "409",           
        "regions_id_region": "42"
      }
    ]
  }
]

Each User has an array of Districts. I want to get a filtered array of Users that has districts with "regions_id_region" = "11" for example. Lodash or Vanilla will be ok. I spend the whole day trying to achieve it without any success. Any help is welcome. Thank you.

Upvotes: 0

Views: 663

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

Here's how you can use filter:

const users = [{
    "displayName": "Alaotra",
    "districts": [{
        "regions_id_region": "11",
        "id_district": "102"
      },
      {
        "regions_id_region": "11",
        "id_district": "101",
      }
    ]
  },
  {
    "displayName": "Alexandre",
    "districts": [{
        "regions_id_region": "42",
        "id_district": "411",
      },
      {
        "id_district": "409",
        "regions_id_region": "42"
      }
    ]
  }
]

const filtered = users.filter(u => u.districts.some(d => d.regions_id_region === '11'))
console.log(filtered)

Upvotes: 2

Related Questions