[英]How can I loop through this array of objects in javascript?
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.我知道我可能会使用一个循环(也许是一个 forEach),但我不确定如何获得我需要的值。 Would I use filter?我会使用过滤器吗?
Use flatMap
with combination of filter
:将flatMap
与filter
组合使用:
const dallasLocations = users.flatMap(user => {
return user.claims.filter(claim => claim.location === 'dallas')
})
You can use flatMap
to flatten the mapped array after filtering the locations which equal to dallas .您可以在过滤等于dallas的位置后使用flatMap
来展平映射的数组。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.