The Now Platform® Washington DC release is live. Watch now!
A few days ago I was talking with someone I'll call Joe about one of our Discovery scripts. Joe was trying to figure out something we were doing in the script, and I finally figured out what was giving him trouble: he'd never run into the notion of using a JavaScript object to represent something. In the specific case he was puzzling over, we used JavaScript objects to represent network adapters — but it could have been anything at all.
For example, suppose you were writing a script that needed to refer to a few hundred locations, many thousands of times. You could do this with queries to the database, but the performance would be slower than you'd like — so you'd like to have this list in memory. Let's further suppose that your script needs to find locations by (presumably unique) name or by (not necessarily unique) zip code. How could you do this?
Here's some code that will do the trick:
var locations = getLocations();
var sd = locations.byName['San Diego'];
gs.log('San Diego: ' + sd.street + ', ' + sd.city + ' ' + sd.zip);
var zip92075 = locations.byZip['92075'];
for (var i = 0; i < zip92075.length; i++) {
var item = zip92075;
gs.log(item.name + ': ' + item.street + ', ' + item.city + ' ' + item.zip);
}
// build the locations object...
function getLocations() {
var answer = {};
answer.locations = [];
answer.byName = {};
answer.byZip = {};
var gr = new GlideRecord('cmn_location');
gr.query();
while (gr.next()) {
// make our object representing a location...
var location = {};
location.name = '' + gr.name;
location.street = '' + gr.street;
location.city = '' + gr.city;
location.zip = '' + gr.zip;
location.country = '' + gr.country;
location.company = '' + gr.company;
// store our new location in a list...
answer.locations.push(location);
// add it to our map of locations by (unique) name...
answer.byName[location.name] = location;
// add it to our map of locations by (not unique) zip code...
if (!answer.byZip[location.zip])
answer.byZip[location.zip] = [];
answer.byZip[location.zip].push(location);
}
return answer;
}
San Diego: 100 Park Boulevard, San Diego 92101
San Diego North: 937 Lomas Santa Fe Drive, San Diego 92075
San Diego West: 123 West Plaza, Solana Beach 92075
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.