Derek Hough
Derek Hough

Reputation: 45

How do i map through array to get array of object?

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

Upvotes: -1

Views: 50

Answers (3)

Athii
Athii

Reputation: 669

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

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

Upvotes: 1

Nick Vu
Nick Vu

Reputation: 15540

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)

Upvotes: 2

Toni Bardina Comas
Toni Bardina Comas

Reputation: 1808

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)

Upvotes: 1

Related Questions