作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试遍历嵌套数组,但无法提取正确的值。
我的 Json 文件
var regions = [
{
"id": 265592,
"longName": "Amsterdam 1",
"name": "ams01",
"statusId": 2,
"regions": [
{
"description": "AMS01 - Amsterdam",
"keyname": "AMSTERDAM",
"sortOrder": 0
}
]
},
{
"id": 814994,
"longName": "Amsterdam 3",
"name": "ams03",
"statusId": 2,
"regions": [
{
"description": "AMS03 - Amsterdam",
"keyname": "AMSTERDAM03",
"sortOrder": 26
}
]
},
{
"id": 1004997,
"longName": "Chennai 1",
"name": "che01",
"statusId": 2,
"regions": [
{
"description": "CHE01 - Chennai ",
"keyname": "CHENNAI",
"sortOrder": 30
}
]
},
我只想将区域数组中的键名提取到数组中。
我的代码工作正常并给我输出:
const regions3 = []
for (let i = 0; i < regions.length; i++) {
const element = regions[i];
const regions1 = (element.regions)
for (let j = 0; j < regions1.length; j++) {
const element1 = regions1[j];
const element2 = element1.keyname;
regions3.push(element2)
console.log(regions3)
}
}
输出
AMSTERDAM
AMSTERDAM03
CHENNAI
我想知道是否有更快的迭代方法而不是将其运行到两个 for 循环中?
谢谢
最佳答案
您可以使用 Array.flatMap()
(在 IE/Edge 中不支持)与 Array.map()
:
const regions = [{"id":265592,"longName":"Amsterdam 1","name":"ams01","statusId":2,"regions":[{"description":"AMS01 - Amsterdam","keyname":"AMSTERDAM","sortOrder":0}]},{"id":814994,"longName":"Amsterdam 3","name":"ams03","statusId":2,"regions":[{"description":"AMS03 - Amsterdam","keyname":"AMSTERDAM03","sortOrder":26}]},{"id":1004997,"longName":"Chennai 1","name":"che01","statusId":2,"regions":[{"description":"CHE01 - Chennai ","keyname":"CHENNAI","sortOrder":30}]}]
const result = regions.flatMap(o =>
o.regions.map(p => p.keyname)
)
console.log(result)
如果您不能使用Array.flatMap()
,您可以使用外部Array.map()
和spread结果转化为Array.concat()
相反:
const regions = [{"id":265592,"longName":"Amsterdam 1","name":"ams01","statusId":2,"regions":[{"description":"AMS01 - Amsterdam","keyname":"AMSTERDAM","sortOrder":0}]},{"id":814994,"longName":"Amsterdam 3","name":"ams03","statusId":2,"regions":[{"description":"AMS03 - Amsterdam","keyname":"AMSTERDAM03","sortOrder":26}]},{"id":1004997,"longName":"Chennai 1","name":"che01","statusId":2,"regions":[{"description":"CHE01 - Chennai ","keyname":"CHENNAI","sortOrder":30}]}]
const result = [].concat(...regions.map(o =>
o.regions.map(p => p.keyname)
))
console.log(result)
关于javascript - 在 JavaScript 中遍历嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619844/
我是一名优秀的程序员,十分优秀!