简体   繁体   中英

ReactJS check value in map

I want to check v.name if exist:

{value.district && value.district.length > 0 ? value.district.map((v,i) => 
    <span key={i}>{v.name} </span>
) : 'Nothing'}

This json:

{
   "current_page":1,
   "data":[
      {
         "id":9,
         "hash":"X3JTgxOQlWk0ZIMBVe41",
         "province":{
            "id":1,
            "name":"yyyy"
         },
         "city":{
            "id":3,
            "name":"xxx"
         },
         "district":[
            {
               "id":107,
               "name":"blah blah"
            }
         ]
      },
      {
         "id":10,
         "hash":"IObmLaVewiNf9cn1ETQy",
         "province":{
            "id":2,
            "name":"zzzzzzzzzzz"
         },
         "city":{
            "id":4,
            "name":"rrrrrrrrrrrrrr"
         },
         "district":[
            null
         ]
      }
   ]
}

Error:

Cannot read property 'name' of null

I tried:

{v.name ? v.name : null}

But still got error. how can I do this?

to solve this check if the item in array is valid or not null like this:

 {value.district && value.district.length > 0 ? value.district.map((v,i) => 
 (v?<span key={i}>{v.name} </span>:null)): 'Nothing'}

Two possible solutions:

You can replace {v.name} with a guard to check that v is not null, which could be either of:

  • {v && v.name}

  • {v? v.name: null} {v? v.name: null} (which is very close to what you tried, but please note the difference - v.name throws the error when v is null so you can't use that to check)

Or filter the array before map -ing it:

{value.district && value.district.length > 0 ? value.district.filter(v => v).map((v,i) =>
    <span key={i}>{v.name} </span>
) : 'Nothing'}

the additional .filter(v => v) simply removes any falsy values, such as null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM