Reputation: 171
I have an array of objects here:
const users = [
{
name: 'xyz',
claims: [
{"location": 'dallas',
"id": '123'},
{"location": 'frisco',
"id": '123'},
{"location": 'plano',
"id": '123'},
]
},
{
name: 'abc',
claims: [
{"location": 'richardson',
"id": '123'},
{"location": 'rowlett',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
},
{
name: 'adr',
claims: [
{"location": 'frisco',
"id": '123'},
{"location": 'irving',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
}
]
I want to get all the locations with dallas as the value. How can I do that? I know I would probably use a loop (maybe a forEach) but I am not exactly sure how I could get the values that I need. Would I use filter?
Upvotes: 1
Views: 65
Reputation: 17019
You can use flatMap
to flatten the mapped array after filtering the locations which equal to dallas.
const users = [
{
name: 'xyz',
claims: [
{"location": 'dallas',
"id": '123'},
{"location": 'frisco',
"id": '123'},
{"location": 'plano',
"id": '123'},
]
},
{
name: 'abc',
claims: [
{"location": 'richardson',
"id": '123'},
{"location": 'rowlett',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
},
{
name: 'adr',
claims: [
{"location": 'frisco',
"id": '123'},
{"location": 'irving',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
}
]
const result = users.flatMap(u => u.claims.filter(c => c.location === 'dallas'))
console.log(result)
Upvotes: 1
Reputation: 38
Use flatMap
with combination of filter
:
const dallasLocations = users.flatMap(user => {
return user.claims.filter(claim => claim.location === 'dallas')
})
Upvotes: 1