首页 > 解决方案 > 展平嵌套的 JSON 对象

问题描述

我有一个像这样的 json 对象:

const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}

我想要这样的输出:即对于每个城市,我想展平数组。

[
  ['My Name', 'London', 'UK'], 
  ['My Name','Mumbai', 'IN'],
  ['My Name','New York', 'US']
]

我已经尝试过扁平化等,但无法弄清楚如何实现这一点。有人可以帮我吗?谢谢,萨西

标签: javascriptjsonnestedflatten

解决方案


这应该可以解决问题!

const people = {
  name: 'My Name',
  cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}

function flattenIt(obj) {
  const name = obj.name;
  const cityData = obj.cities;
  return cityData.map(({city, country}) => [name, city, country])
}

console.log(flattenIt(people));


推荐阅读