简体   繁体   中英

Better way to Check for values

Is there a more elegant way to do this?

if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}

Meaning the response && response.body && response.body.data ?

Php has something called isset(), but Js does not seem to have that function. Here is one of my favorites that I found on stack overflow a while back.

user = {
  loc: {
        lat: 50,
        long: 9
  } 
}

user2 = null; 

has = function(obj, key) {
return key.split(".").every(function(x) {
    if(typeof obj != "object" || obj === null || !( x in obj)) {
        return false;          
    }
    obj = obj[x];
    return true;
});
}

console.log(has(user, 'loc.lat')); //true 
console.log(has(user, 'loc')); //true
console.log(has(user, 'loc.lat.ll')); // false
console.log(has(user2, 'd')); //false

If you won't check an object existence before calling its property, you can get exception and the execution stop. Therefore, someone would suggest a try catch.

However, from my experience, it is better to check this way, explicit, easy to read and maintenance code is always good.

No. But if it is a REST API (which looks like it is) I would recommend using a library for validations. And joi is the best when you have to perform nested validations.

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