0

I have a Json data something like this

{
 A: {name: 'a', date: 'x'}
B: {name: 'b', date: 'x'}
C: {name: 'c', date: 'x'}
D: {name: 'd', date: 'x'}

}

I am trying to list all the name. However, i get an error

.data.map is not a function

My code looks something like this:

 {data.map((item) => {
    return(
      <div>
     {item.name}
    </div> )
 })}

Any help would be appreciated! Thanks

James Lee
  • 656
  • 1
  • 7
  • 22

3 Answers3

1

What you have there is an object not an array and .Map() is an Array method.

You can do something similar with an object this way

 {data && Object.values(data).map((propVal) => {
    return(
      <div>
     {propVal}
    </div> )
 })}

You can also use Object.entries() each entry is an array with two elements. entry[0] is the key while entry[1] is the value. This way you can also add a check for the prop name.

 {data && Object.entries(data).map((entry) => {
            if(entry[0] === 'name') {
               return(
                  <div>
                 {propVal}
                </div> )
             })}    
} 

Hope it helps :)

0

You've to convert your object values to array.

{data && Object.values(data).map((item) => {
    return(
      <div>
     {item.name}
    </div> )
 })}
Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21
0

try this

Object.values(data).map( // the rest

Object.values will give you an array of a given object's own enumerable property values.

Incepter
  • 2,711
  • 15
  • 33