简体   繁体   中英

How to get a value of Object which possible has a undefined key?

something like angular 's $parse service.

If there is an object like this:

const obj = {
  items: [
    {
      store: {
        type: ''
      }
    }
  ]
};

watch : the keys items and store and type possible are undefined , or no exist.

I want to get the first item 's type, here is my code:

const firstItem = obj.items[0] || {};
const store = firstItem.store || {};
const type = store.type || 'computer';

I think there is a better way to do this. I know angular 's $parse service is simple to do that. Is there a way like angular 's $parse service or any other ideas? Thanks!

Why not to use try catch.

var type;
try {
    type = obj.items[0].store.type;
}
catch {
    type = 'computer';
}
if(!angular.isUndefined(obj))
{
   if(angular.isArray(obj.items)){
       // Do something
   }
}

Is there you need ?

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