将JSOn对象转换为平面JSON数组

时间:2018-12-10 20:39:28

标签: javascript node.js

我有一个嵌套的JSON对象,该对象是从mongoDB查询中获取的,我想将其转换为平面JSON数组。我正在使用嵌套的mondo文档,但我想以更易读的方式显示数据。我的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"
                }
            ]
        }
    ]
}

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

[{
"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);
    });
}

3 个答案:

答案 0 :(得分:1)

我相信这将执行您寻求的转变:

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);

答案 1 :(得分:0)

我认为您需要使用map函数,并将嵌套数组中的每个对象转换为要获取的对象。如果我不了解您,那么您将需要这样的东西:

let desiredArray = country.region.map(x => {
    country:x.country,
    region:x.region,
    cities:x.city
})

有点困惑,无法理解您真正想要的东西,但是我认为您可以开始使用它了。

答案 2 :(得分:0)

就像Node的典型情况一样... 有一个软件包!一个流行的软件包叫做flat(零下垂!)。 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://github.com/mster/fireferret/blob/e99b6e8f23d4a0783c8a0706cd163093936d6c69/lib/utils/flatmapper.js#L6-L50

相关问题