展平嵌套的 JSON 对象
Posted
技术标签:
【中文标题】展平嵌套的 JSON 对象【英文标题】:Flatten nested JSON object 【发布时间】:2021-10-19 18:29:19 【问题描述】:我有一个这样的 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']
]
我尝试过 flatten 等,但不知道如何实现这一点。 有人可以帮我吗? 谢谢, 萨西
【问题讨论】:
【参考方案1】:如果你想要 JSON 输出:
const people =
name: 'My Name',
cities: [city: 'London', country: 'UK',city: 'Mumbai', country: 'IN',city: 'New York', country: 'US'],
let result = people.cities.map(data =>
return
name: people.name,
city: data.city,
country: data.country
)
console.log(result)
为多人扩展:
const peopleExtended = [
name: 'My Name',
cities: [
city: 'London',
country: 'UK'
,
city: 'Mumbai',
country: 'IN'
,
city: 'New York',
country: 'US'
],
,
name: 'Person 2',
cities: [
city: 'Birmingham',
country: 'UK'
,
city: 'Delhi',
country: 'IN'
,
city: 'New York',
country: 'US'
],
]
function flattenCities(person)
return person.cities.map(data =>
return
name: person.name,
city: data.city,
country: data.country
)
peopleExtended.forEach(person =>
let flatArray = flattenCities(person);
console.log(person.name, flatArray)
)
【讨论】:
这与 JSON 完美搭配。为了扩展它,如果我有一个 json 数组,例如: const people =[ name: 'My Name', urban: [city: 'London', country: 'UK',city: 'Mumbai', country: 'IN',city: 'New York', country: 'US'], , name: 'Person 2', 城市: [city: 'Birmingham', country: 'UK', city: 'Delhi', country: 'IN',city: 'New York', country: 'US'], ] 这是如何工作的?谢谢 当然!只需将扁平化代码放入一个函数中,然后在每次遍历一个人时调用它。查看我的编辑。【参考方案2】:这应该可以解决问题!
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));
【讨论】:
你是明星!优秀的答案。我挣扎了几个小时,你让我的一天变得很轻松。以上是关于展平嵌套的 JSON 对象的主要内容,如果未能解决你的问题,请参考以下文章
使用 Azure Synapse pyspark 过滤器根据嵌套对象的数据类型展平嵌套的 json 对象