简体   繁体   English

如何获得可能具有未定义键的Object值?

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

something like angular 's $parse service. 类似于angular$parse服务。

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. watch :可能的键items以及storetype undefined ,或者不存在。

I want to get the first item 's type, here is my code: 我想获取第一item的类型,这是我的代码:

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. 我知道angular$parse服务很容易做到这一点。 Is there a way like angular 's $parse service or any other ideas? 有没有类似angular$parse服务或其他任何想法的方法? Thanks! 谢谢!

Why not to use try catch. 为什么不使用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 ? 有需要吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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