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

时间:2018-12-05 01:13:16

标签: javascript node.js

我有一个嵌套的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"
  }
]

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

1 个答案:

答案 0 :(得分:1)

最简单的方法是循环遍历并创建一个数组。您可以使用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)