简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM