0

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.

3
  • Add your attempt to the question Commented Feb 12, 2021 at 16:55
  • What do you want the result to look like? Commented Feb 12, 2021 at 16:56
  • Does this answer your question? javaScript filter nested objects and arrays Commented Feb 12, 2021 at 17:00

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you all for your answers, i waq very useful. What would be the best approach if "regions_id_region" is in an array? ["11","42" ]?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.