首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将嵌套JSON数组转换为平面JSON数组

将嵌套JSON数组转换为平面JSON数组
EN

Stack Overflow用户
提问于 2018-12-05 09:13:16
回答 1查看 274关注 0票数 0

我有一个嵌套的JSON数组,它是从一个mongoDB查询中获取的,我想转换成扁平的JSON mondo使用嵌套的mondo文档,但我想以一种更具可读性的方式显示数据。我的JSON结构如下:

代码语言:javascript
复制
[{
     "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中修改我的数据,以达到以下结果。

代码语言: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"
  }
]

获得这个结果的最简单方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-05 09:21:13

最简单的方法是循环遍历并创建一个数组。您可以使用reduce()实现这一点

代码语言:javascript
复制
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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53623764

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档