Sasi C
Sasi C

Reputation: 23

Flatten nested JSON object

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

Answers (2)

itsisaac19
itsisaac19

Reputation: 540

If you want JSON output:

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)

To scale this for multiple people:

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

async await
async await

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

Related Questions