简体   繁体   中英

How to check whether an object key exists or not in JavaScript?

I am getting an object from backend and that object has several keys and values. According to the database data sometimes some of the keys won't be available. So I have used ternary operator for it but still, it is not working.

 `
  <tr>
     <td>
         ${(df[temp].image.status)?df[temp].image.status:'Not Assigned'}
     </td>
  </tr>
  `

Expected result: Whether an "image" key is there or not there shouldn't be any error. Either it should be some status or 'Not Assigned';

Current result: TypeError: df[temp].image is undefined

Anyone any idea why this is happening?

You are checking on already undefined value. First you need to verify that image exists and then you can access its fields.

<tr>
    <td>
        ${(df[temp].image && df[temp].image.status) ? (df[temp].image.status) : 'Not Assigned'}
    </td>
</tr>

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