[英]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
以及store
和type
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.