born2gamble
born2gamble

Reputation: 207

React JSX mapping through data where sometimes a data field is missing

im looping through data This is react.js / jsx If I am pulling 100 items, none will show because of one being undefined. I just want it to display "0" if it is undefined, and show the size if it is there.

Error: Cannot read property size of undefined.

Example of data,

Item={
    color:blue,
    size:medium,
    }
Item={
    color:red
    }

I am mapping through the data.

Im essentially doing this :

 return items.map((item, i) => {
    return( {item.size})

I have also tried {item.size ? "itWorks" : "0"} as a test, and I get the same error.

Upvotes: 0

Views: 44

Answers (3)

Vikram Mahishi
Vikram Mahishi

Reputation: 3321

You should do,

return (

items && items.map(function(item, id){ .....}))

So the loop goes through when items array is of some length otherwise it exits

Upvotes: 1

aravind_reddy
aravind_reddy

Reputation: 5476

It is better to use object.hasOwnProperty('property') to check whether your object has a particular property or not . for your case it is:

{item.hasOwnProperty('size') ? "itWorks" : "0"} 

Upvotes: 1

StackedQ
StackedQ

Reputation: 4139

The error is:

Error: Cannot read property size of undefined

It means item is undefined, So you gotta check for item and item.size.

Upvotes: 1

Related Questions