1

I have the following const:

const dictionaryData = {
  "Car1": "Ford",
  "Car2": "Dodge",
  "Car3": "Chevrolet",
  "Car4": "Nissan",
  "Car5": "Toyota",
  "Car6": "Honda",
};

What I want to do is loop through the CarN elements and render a span with the brand value. Something like this:

<span key="Car1">Ford</span>

I tried doing a dictionaryData.map() but this is not working (getting dictionary.map() is not a function error), I think that it's because is not an array. So my question is: how can I through that const and access to the brand values? Maybe is not possible change that const to an array.

User1899289003
  • 850
  • 2
  • 21
  • 40

2 Answers2

2

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well. read more

Object.entries(dictionaryData).map(([key, value]) => {
 return <span key={key}>{value}</span>
})
Eduard
  • 1,319
  • 6
  • 12
0

You'll want to iterate over an array with map(). You could grab the object keys with Object.keys(), then use the value of the key at each iteration to grab the value from the original object.

isherwood
  • 58,414
  • 16
  • 114
  • 157