Reputation: 23
I have a json object like this:
const people = {
name: 'My Name',
cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: 'US'}],
}
I would like the output like this: i.e for each cities, I would like to flatten array.
[
['My Name', 'London', 'UK'],
['My Name','Mumbai', 'IN'],
['My Name','New York', 'US']
]
I have tried flatten etc and could not figure out how to achieve this. Could someone please help me? Thanks, Sasi
Upvotes: 0
Views: 1276
Reputation: 540
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)
})
Upvotes: 1
Reputation: 2395
This should do the trick!
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));
Upvotes: 2