Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use .map() only when there is an array?

I am new to react and I am passing an item prop. Some of the items has an empty array in items.modifiers. When I use an if an if condition i still get an error that "Cannot read property 'map' of undefined " Below is my code. Any help would be really appreciated.

const NewModal = ({ item }) => {
  if (item.modifiers !== "") {
    item.modifiers.map((modifier) => console.log(modifier.cat_name));
  }
};

return [
  {
    items: [
      {
        item_id: 1,
        item_name: "Philadelphia Steak Sandwich",

        modifiers: {
          cat_name: " Choose a side",
          mod_items: [
            { mod_item_name: "French Fries", price: 1 },
            { mod_item_name: "Cole Slaw", price: 2 },
          ],
        },
      },
      {
        item_id: 2,
        item_name: "Philadelphia Steak Sandwich Deluxe",

        modifiers: "",
      },
    ],
  },
];

like image 243
json Avatar asked Sep 20 '25 02:09

json


1 Answers

Use Array.isArray() first to check whether the item you're trying to map is of type Array.

const NewModal = ({item}) => {

    if(Array.isArray(item.modifiers) {
      item.modifiers.map((modifier)=> console.log(modifier.cat_name));
    }
}
like image 138
Yair Cohen Avatar answered Sep 22 '25 01:09

Yair Cohen