Home > Mobile >  Convert array with objects
Convert array with objects

Time:09-16

I have an array with data:

const data = [
  {
    groupName: 'groupName1',
    types: [
      {
        name: 'name1',
        displayName: 'displayName1'
      },
      {
        name: 'name2',
        displayName: 'displayName2'
      },
    ]
  },
  {
    groupName: 'groupName2',
    types: [
      {
        name: 'name3',
        displayName: 'displayName3'
      },
      {
        name: 'name4',
        displayName: 'displayName4'
      },
    ]
  },
]

I need to transform this array so that an extra groupName field is added to each object. The output should be an array with objects as shown below:

const resultData = [
  {
    groupName: 'groupName1',
    name: 'name1',
    displayName: 'displayName1'
  },
  {
    groupName: 'groupName1',
    name: 'name2',
    displayName: 'displayName2'
  },
  {
    groupName: 'groupName2',
    name: 'name3',
    displayName: 'displayName3'
  },
  {
    groupName: 'groupName2',
    name: 'name4',
    displayName: 'displayName4'
  },
]

I tried to do it through the map array method

const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]

const resultData = data.map((item) => {
  item.types.map((item1) => {
    return {
      ...item1,
      groupName: item.groupName
    }
  })

  return item
})

console.log(resultData)

But this does not return the array that I need. Please tell me how I can transform this array so that each object has the correct structure? Thank you in advance!

CodePudding user response:

Replace the outer Array.map() call with Array.flatMap() to create a flat array, and return the result of the internal map call, and not the original item.

const data = [{"groupName":"groupName1","types":[{"name":"name1","displayName":"displayName1"},{"name":"name2","displayName":"displayName2"}]},{"groupName":"groupName2","types":[{"name":"name3","displayName":"displayName3"},{"name":"name4","displayName":"displayName4"}]}]

const resultData = data.flatMap(({ types, groupName }) => 
  types.map(item => ({
    ...item,
    groupName
  }))
)

console.log(resultData)

CodePudding user response:

I would use reduce.

data.reduce((carry, {types, groupName}) => carry.concat(types.map(d => ({...d, groupName}))), []);
  • Related