Using JavaScript 'IN' Operator

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2012 02:09 PM
JavaScript has a nifty operator called IN which allows you to process a query on an array of options. Example:
if ( foo == "bar" || foo == "foobar" || foo == "foo" )
{
//...
}
// can be written as
if ( foo in { bar:1, foobar:1, foo:1 } )
{
//...
}
Here are a few examples of the "IN" operator being used in ServiceNow:
In Conditions:
Instead of: current.state != 3 && current.state != 4 && current.state != 6 && current.state != 7
Do this: !(current.state in { 3:1, 4:1, 6:1, 7:1 })
In Business Rules:
var gr = new GlideRecord('incident');
gr.addQuery('state', 'IN', '1,4,6,7');//match on records that have a state of 1,4,6, or 7
gr.query();
- 9,366 Views
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2012 03:26 PM
Thanks for pointing out the query shortcut Eric, it's definitely makes scripting easier in certain cases.
I just wanted to clear up a few things to avoid confusion.
The javascript "in" operator works on object properties not arrays. Hence the curly braces and property values of 1.
If you're looking for something that checks an array for a value, checkout the ArrayUtil().contains method.
As for the the "IN" query operator, that does work with delim strings as you showed as well as arrays. This comes in handy when you're collecting sys_ids from one query, storing them into an array then need to query another table for those ids.
//something like
var ids = [];
for (some loop) {
ids.push(some id);
}
//some gr query
gr.addQuery("sys_id","IN",ids);
Sorry for the generic code, but you should get the picture.