我有一个像这样的 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']
]
我试过展平等,但不知道如何实现这一点。有人可以帮我吗?谢谢,萨西
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)
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句