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

2
  • map is an array method, it does not exist on objects. Commented May 21, 2020 at 15:48
  • If you don't need the object keys, just use object.values Commented May 21, 2020 at 15:51

3 Answers 3

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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

object.entries does not work like this
Object.values() works, but he use only the name attribute.
I added object entries as an alternative
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.

1 Comment

Thank you! it works!
0

You've to convert your object values to array.

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

3 Comments

I've edited the answer, my bad. I didn't see that the data was an object.
object.entries gives an array of arrays
Yes, its object.values which will give array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.