Home > OS >  How do i map through array to get array of object?
How do i map through array to get array of object?

Time:07-13

I have an array called data. How do i extract sub_data? Just need the sub_data part for each object.

const data = [
  {
    id: 1,
    title: 'Logo'
    sub_data: [
      {
        id: 2,
        title: 'Company Logo'
      },
      {
        id: 3,
        title: 'Website Logo'
      }, 
    ]
  },
  {
    id: 2,
    title: 'Brands'
    sub_data: [
      {
        id: 25,
        title: 'Company Brands'
      },
      {
        id: 3,
        title: 'Website Brands'
      }, 
    ]
  }
]

Example output will get two outputs because there is 2 objects:

const subData = [
      {
        id: 2,
        title: 'Company Logo'
      },
      {
        id: 3,
        title: 'Website Logo'
      }, 
]


const subData = [
       {
        id: 25,
        title: 'Company Brands'
      },
      {
        id: 3,
        title: 'Website Brands'
      },  
]

Not very sure how to use the map function just to get sub_data in the correct structure

CodePudding user response:

You can use flatMap to get sub_data in one array

const data = [
  {
    id: 1,
    title: 'Logo',
    sub_data: [
      {
        id: 2,
        title: 'Company Logo'
      },
      {
        id: 3,
        title: 'Website Logo'
      }, 
    ]
  },
  {
    id: 2,
    title: 'Brands',
    sub_data: [
      {
        id: 25,
        title: 'Company Brands'
      },
      {
        id: 3,
        title: 'Website Brands'
      }, 
    ]
  }
]

const result = data.flatMap(item => item.sub_data)

console.log(result)

CodePudding user response:

If you want an array with the sub_data objects you can just map the original array:

const data = [
  {
    id: 1,
    title: 'Logo',
    'sub_data'
    : [
      {
        id: 2,
        title: 'Company Logo'
      },
      {
        id: 3,
        title: 'Website Logo'
      }, 
    ]
  },
  {
    id: 2,
    title: 'Brands',
    sub_data: [
      {
        id: 25,
        title: 'Company Brands'
      },
      {
        id: 3,
        title: 'Website Brands'
      }, 
    ]
  }
]

const mappedData = data.flatMap(obj => obj.sub_data)

console.log(mappedData)

CodePudding user response:

Another solution would be to use the .forEach function of javascript.

const subData = [];
data.forEach(item => subData.push(...item.sub_data))

CodePudding user response:

const subData = array.find((obj) => obj.id === 2)

It can be undefined if does not contain id === 2

  • Related