简体   繁体   中英

How to tell if a property in a sub-object exists?

I have a object defined as

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

How can I tell whether interval in aggs.times.date_histogram exists, so that I can manipulate it?

Clarification: I can not be sure that any of the parent objects to interval exist.

You can check it with typeof :

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

Another method is using the in keyword (this one is prettier and more obvious imho)

if('interval' in aggs.times.date_histogram) {
    // ... exists ...
}

The above is assuming aggs.times.date_histogram exists (and doesn't need an existence check)


Update : For checking the existence of everything leading to the value you need, you can use this:

function getProp(_path, _parent) {
   _path.split('.').forEach(function(_x) {
       _parent = (!_parent || typeof _parent !== 'object' || !(_x in _parent)) ? undefined : _parent[_x];
   });
   return _parent;
}

You can call it like:

getProp('aggs.times.date_histogram.interval', parent_of_aggs);

Will return the value of interval if it is defined, else it will return undefined

Assuming the value is always a non-blank string, just test it for truthiness:

if (aggs.times.date_histogram.interval) {
    // Use it
}

You might cache the result of those property lookups. Though it's unlikely to really matter for performance, it may be useful for code maintainability:

var interval = aggs.times.date_histogram.interval;
if (interval) {
    // Use it
}

If you need to worry that each level may not exist, it gets more verbose:

if (aggs &&
    aggs.times &&
    aggs.times.date_histogram &&
    aggs.times.date_histogram.interval) {
    // Use it
}

There's a question with several answers about writing a function for that.

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

Use this:

if(test.aggs.times.date_histogram.interval) {
    alert('true'); //your code here
} else {
    alert('false'); //your code here
}

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