我有一个嵌套的JSON数组,它是从一个mongoDB查询中获取的,我想转换成扁平的JSON mondo使用嵌套的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"
}
]
获得这个结果的最简单方法是什么?
发布于 2018-12-05 09:21:13
最简单的方法是循环遍历并创建一个数组。您可以使用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)
https://stackoverflow.com/questions/53623764
复制相似问题