如何判断子对象中的属性是否存在?

时间:2015-06-04 13:39:53

标签: javascript

我有一个定义为

的对象
{
    "query" :
    {
        /* snip */
    },
    "aggs":
    {
        "times" :
        {
            "date_histogram" :
            {
                "field" : "@timestamp",
                "interval" : "15m",
                "format" : "HH:mm",
                "min_doc_count" : 0
            }
        }
    }
};

如何判断interval中的aggs.times.date_histogram是否存在,以便我可以操纵它?

澄清:我无法确定interval的任何父对象是否存在。

3 个答案:

答案 0 :(得分:3)

您可以使用typeof

进行检查
if(typeof aggs.times.date_histogram['interval'] !== 'undefined') {
    // ... exists ...
}

另一种方法是使用in关键字(这个更漂亮,更明显的imho)

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

答案 1 :(得分:2)

假设值始终是非空字符串,只需测试它的真实性:

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
}

关于为此编写函数有a question with several answers

答案 2 :(得分:0)

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
}
相关问题