我有一个嵌套的JSON对象,它来自一个mongoDB查询,我希望使用嵌套的mondo文档将其转换为平面的JSON数组.I,但是我想以更易读的方式显示数据。我的JSON有以下结构:
{
"country": "Country A",
"_id": "1"
"regions": [{
"region": "region A1",
"cities": [{
"city": "city A11"
},
{
"city": "city A12"
}
]
},
{
"region": "region A2",
"cities": [{
"city": "city A21"
},
{
"city": "city A22"
}
]
}
]
}
我只想显示重要的信息,而不是嵌套数组的结构。如何修改Javascript中的数据以获得以下结果。
[{
"country": "Country A",
"region":"Region A1",
"city": "City A11"
},
{
"country": "Country A",
"region":"Region A1",
"city": "City A12"
},
-------------
{
"country": "Country A",
"region":"Region A2",
"city": "City A22"
}]
我试过这样做,但这行不通。
exports.get_places = (req, res, next) => {
Place.findOne({_id:req.params.id})
.then(data => {
let flat = arr.reduce((arr, {country, regions}) => {
regions.forEach(({region, cities}) => {
cities.forEach(({city}) => {
arr.push({country, region, city})
})
})
return arr
}, [])
console.log(flat)
})
.catch(error => {
return next(error);
});
}
发布于 2018-12-10 13:22:07
我相信这将实现你所寻求的转变:
const country = {
"country": "Country A",
"_id": "1",
"regions": [
{
"region": "region A1",
"cities": [
{
"city": "city A11"
},
{
"city": "city A12"
}
]
},
{
"region": "region A2",
"cities": [
{
"city": "city A21"
},
{
"city": "city A22"
}
]
}
]
};
const flat = country.regions.flatMap(({region, cities}) =>
cities.map(({city}) => ({country: country.country, region, city})
));
console.log(flat);
发布于 2018-12-10 12:55:39
我认为您需要使用map函数,并将嵌套数组中的每个对象转换为要获取的对象。如果我对你好,你就需要这样的东西:
let desiredArray = country.region.map(x => {
country:x.country,
region:x.region,
cities:x.city
})
不知道你真正想要的是什么有点困惑,但我认为你可以开始处理这个问题。
发布于 2020-08-16 00:32:07
作为Node的典型案例..。这有个包裹!一个流行的名为flat
(零deps!)。https://www.npmjs.com/package/flat
来自他们的自述:
var flatten = require('flat')
flatten({
key1: {
keyA: 'valueI'
},
key2: {
keyB: 'valueII'
},
key3: { a: { b: { c: 2 } } }
})
// {
// 'key1.keyA': 'valueI',
// 'key2.keyB': 'valueII',
// 'key3.a.b.c': 2
// }
您也可以实现自己的!:)
如果您需要一些提示,我已经在我最近的一个项目中实现了一个提示,但它返回一个数组。
https://stackoverflow.com/questions/53713291
复制相似问题