Home > Software engineering >  Move an inner array of objects to the outer array of objects
Move an inner array of objects to the outer array of objects

Time:01-06

Array example:

const data = [
{id:3333 name:'a' sites: []}, 
{id:2343 name:'b' sites: [
{id: 3322, name: 'f' sites: null},
{id: 3211, name: 'v' sites: null},
]
},
{id:4444 name:'c' sites: []},
]

I want the data to look like:

const newData = [
{id:3333 name:'a' sites: []}, 
{id:2343 name:'b' sites: []},
{id: 3322, name: 'f' sites: null}, 
{id: 3211, name: 'v' sites: null},
{id:4444 name:'c' sites: []},
]

I did this bellow, but I feel like there is a better way. I am worried I am mutating the data or something.

  const newData: ISite[]=[]
  data?.forEach(site => {
    if (!site.sites) {
      newData.push(site)
    }
    else{
      newData.push(site)
      site.sites.forEach(x=> newData.push(x))
    }
  })

CodePudding user response:

You can use flatMap like this:

const data = [{
    id: 3333,
    name: 'a',
    sites: []
  },
  {
    id: 2343,
    name: 'b',
    sites: [{
        id: 3322,
        name: 'f',
        sites: null
      },
      {
        id: 3211,
        name: 'v',
        sites: null
      },
    ]
  },
  {
    id: 4444,
    name: 'c',
    sites: []
  },
]

const newData = data.flatMap(site => {
    if (!site.sites) {
        return site
    }

    return [{...site, sites: []}, ...site.sites]
})

console.log(newData)

  • Related