Mina Hawker
Mina Hawker

Reputation: 111

Map through an array of objects in js/react

I need an array of alt strings. I can map the array with name strings, but can't get it to return the "alt". This is what I tried:

const data = [
  { name: "Apple", alt: "Fruit" },
  { name: "Banana", alt: "Fruit" },
  { name: "Potatoe", alt: "Vegetable" },
  { name: "Lentil", alt: "Legume" }];
  <span>
      {data.map(item => {
        return (
         <Button item={item.alt.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

To get an array of namestrings, this worked:

  <span>
      {data.map(item => {
        return (
         <Button key={item.name} item={item.name.toUpperCase()}>
         {item}
         </Button>
         );
       })}
  </span>

This is the error: TypeError: Cannot read property 'toUpperCase' of undefined

Upvotes: 1

Views: 107

Answers (2)

Ankit Verma
Ankit Verma

Reputation: 94

I think you are trying to create a button please look below

The below code is modified to use key in map function as each of your record is unique and react keys are useful when working with dynamically created components or when your data are altered . Setting the key value will keep your components uniquely identified after the change and they also help in performance.You can read the below blog it explains well about using keys. https://programmingwithmosh.com/react/why-do-i-need-keys-in-react-lists/

 const data = [
      {id:1, name: "Apple", alt: "Fruit" },
      {id:2 ,name: "Banana", alt: "Fruit" },
      {id:3, name: "Potatoe", alt: "Vegetable" },
      {id:4, name: "Lentil", alt: "Legume" }
    ];
    function App() {
      return (
        <span>
          {data.map((item) => (
            <button key={item.id}>{item.alt.toUpperCase()}</button>
          ))}
        </span>
      );
    }

Use this link it is working here https://codesandbox.io/s/friendly-wave-t117u

Upvotes: 2

SiddAjmera
SiddAjmera

Reputation: 39482

Give this a try:

<span>{
  data.map(
    (item, index) => <button 
      alt={item.alt.toUpperCase()} 
      key={someKeyHere}>
        {item.alt.toUpperCase()}
      </button>)
}</span>

Here's a Working Sample StackBlitz for your ref.

Upvotes: 0

Related Questions