gpt4 book ai didi

javascript - 在 JavaScript 中遍历嵌套数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:36 25 4
gpt4 key购买 nike

我正在尝试遍历嵌套数组,但无法提取正确的值。

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com