Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map through an object with array of object

I have an object which has an array of objects and 2 other key-value pairs.
I get stuck on how to display the object values. I got an error showing 'TypeError: obj.map is not a function.

This is my code

import React from 'react'

function MapObj() {

    const obj = {
        items: [
          {
          id: 1,
          title: 'Pizza'
        },
        {
         id: 2,
         title: 'Hot-Dog'
       }
       ],
        total: 200,
        isEmpty: false
      };

  const mappedObj = obj.map(item => {
      return (
       <>
         <div key={item.items.id}>
          <h2>{item.items.title}</h2>
         </div>
        <p>{item.total}</p>
        <p>{item.isEmpty}</p>
       </>
      )
  })

  return (
    <div style={{textAlign: 'center', color: 'maroon'}}>
        {mappedObj}
    </div>
  )
}

export default MapObj

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The function map does not exist on an object but only on an array.

Try to use map on object.items instead on the object directly. Also you can access the property using item.id for example directly.

Like this:

import React from 'react'

function MapObj() {

    const obj = {
        items: [
          {
          id: 1,
          title: 'Pizza'
        },
        {
         id: 2,
         title: 'Hot-Dog'
       }
       ],
        total: 200,
        isEmpty: false
      };

  const mappedObj = obj.items.map(item => {
      return (
       <>
         <div key={item.id}>
          <h2>{item.title}</h2>
         </div>
        <p>{obj.total}</p>
        <p>{obj.isEmpty}</p>
       </>
      )
  })

  return (
    <div style={{textAlign: 'center', color: 'maroon'}}>
        {mappedObj}
    </div>
  )
}

export default MapObj
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading