最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i use .map() only when there is an array? - Stack Overflow

programmeradmin1浏览0评论

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: "",
      },
    ],
  },
];

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: "",
      },
    ],
  },
];

Share Improve this question edited Dec 20, 2020 at 12:59 AbsoluteBeginner 2,2633 gold badges14 silver badges24 bronze badges asked Dec 20, 2020 at 4:56 jsonjson 2174 silver badges9 bronze badges 2
  • 1 Does this answer your question? How to check if an object is an array? – ggorlen Commented Dec 20, 2020 at 4:59
  • Just check if it's undefined, an object that has a map property/function, or is an array, depending on your app's needs. I'm not sure what checking against the empty string would help avoid. A piece of data that could be an empty string or could be an array sounds like a pretty brittle situation to be in. – ggorlen Commented Dec 20, 2020 at 5:00
Add a ment  | 

3 Answers 3

Reset to default 4

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));
    }
}

You need to ensure your data is an array in the first place. Then you can check whether the array is ready or not.

You should ensure data type is consistent, this is a given.

While waiting for the data to populate (probably from an API call), instead of if-else you can use null propagation operators / optional chaining

Then you can call something like this with a single question mark before the dot.

const newArray = item?.modifier?.map(item => do something)

This way it will suppress the undefined error.

Another step you need to take is conditional rendering.

For example

if (!data?.length) return null

//OR

if (!data?.length) return <div>data is loading</div>

You can simply do that by checking if every required condition is met and then by looping the modifiers array,

item && item.modifiers && item.modifiers.length && item.modifiers.map((modifier)=> console.log(modifier.cat_name))
发布评论

评论列表(0)

  1. 暂无评论