[英]How to tell if a property in a sub-object exists?
我有一个对象定义为
{
"query" :
{
/* snip */
},
"aggs":
{
"times" :
{
"date_histogram" :
{
"field" : "@timestamp",
"interval" : "15m",
"format" : "HH:mm",
"min_doc_count" : 0
}
}
}
};
如何判断aggs.times.date_histogram
interval
是否存在,以便可以进行操作?
澄清:我不确定要interval
任何父对象是否存在。
您可以使用typeof
进行检查:
if(typeof aggs.times.date_histogram['interval'] !== 'undefined') {
// ... exists ...
}
另一种方法是使用in
关键字(这个关键字更漂亮,更明显是恕我直言)
if('interval' in aggs.times.date_histogram) {
// ... exists ...
}
上面假设aggs.times.date_histogram
存在(并且不需要存在检查)
更新 :要检查是否存在所有需要价值的东西,可以使用以下方法:
function getProp(_path, _parent) {
_path.split('.').forEach(function(_x) {
_parent = (!_parent || typeof _parent !== 'object' || !(_x in _parent)) ? undefined : _parent[_x];
});
return _parent;
}
您可以这样称呼它:
getProp('aggs.times.date_histogram.interval', parent_of_aggs);
如果已定义,将返回interval
的值,否则将返回undefined
假设该值始终是一个非空白字符串,请对其进行真实性测试:
if (aggs.times.date_histogram.interval) {
// Use it
}
您可能会缓存那些属性查找的结果。 尽管对性能的影响并不大,但对于代码的可维护性可能很有用:
var interval = aggs.times.date_histogram.interval;
if (interval) {
// Use it
}
如果您担心每个级别可能都不存在,它将变得更加冗长:
if (aggs &&
aggs.times &&
aggs.times.date_histogram &&
aggs.times.date_histogram.interval) {
// Use it
}
test = {
"query" :
{
/* snip */
},
"aggs":
{
"times" :
{
"date_histogram" :
{
"field" : "@timestamp",
"interval" : "15m",
"format" : "HH:mm",
"min_doc_count" : 0
}
}
}
};
用这个:
if(test.aggs.times.date_histogram.interval) {
alert('true'); //your code here
} else {
alert('false'); //your code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.