gpt4 book ai didi

javascript - 将嵌套 JSON 数组转换为平面 JSON 数组

转载 作者:行者123 更新时间:2023-12-03 00:36:50 25 4
gpt4 key购买 nike

我有一个嵌套的 JSON 数组,它从 mongoDB 查询中获取,我想将其转换为平面 JSON。我正在使用嵌套的 mondo 文档,但我想以更易读的方式显示数据。我的 JSON 具有以下结构:

[{
"country": "Country A",
"regions": [{
"region": "region A1",
"cities": [{
"city": "city A11"
},
{
"city": "city A12"
}
]
},
{
"region": "region A2",
"cities": [{
"city": "city A21"
},
{
"city": "city A22"
}
]
}
]
},
{
"country": "Country B",
"regions": [{
"region": "region B1",
"cities": [{
"city": "city B11"
},
{
"city": "city B12"
}
]
},
{
"region": "region B2",
"cities": [{
"city": "city B21"
},
{
"city": "city B22"
}
]
}
]
}
]

我只想显示重要信息,而不是嵌套数组的结构。我如何在 Javascript 中修改我的数据以获得以下结果。

[
{
"country": "Country A",
"region":"Region A1",
"city": "City A11"
},
{
"country": "Country A",
"region":"Region A1",
"city": "City A12"
},
-------------
{
"country": "Country B",
"region":"Region B1",
"city": "City B11"
},
-----------
{
"country": "Country B",
"region":"Region B2",
"city": "City B22"
}
]

达到这个结果的最简单方法是什么?

最佳答案

最简单的方法是循环并创建一个数组。您可以使用reduce()来做到这一点:

let arr = [{"country": "Country A","regions": [{"region": "region A1","cities": [{"city": "city A11"},{"city": "city A12"}]},{"region": "region A2","cities": [{"city": "city A21"},{"city": "city A22"}]}]},{"country": "Country B","regions": [{"region": "region B1","cities": [{"city": "city B11"},{"city": "city B12"}]},{"region": "region B2","cities": [{"city": "city B21"},{"city": "city B22"}]}]}]

let flat = arr.reduce((arr, {country, regions}) => {
regions.forEach(({region, cities}) => {
cities.forEach(({city}) => {
arr.push({country, region, city})
})
})
return arr
}, [])
console.log(flat)

关于javascript - 将嵌套 JSON 数组转换为平面 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623764/

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