Yes, it's possible to use a variable to perform a query. Remember, though: The key value must be present in the object you're querying. In your example, userChoice
is not a property of myMapObject
, so it won't match.
Here's an example related to those in the ScriptDb Service Documentation. The findOlderThan()
function accepts a parameter age
which is used in a query of people
objects. Those people
objects have 4 properties, type
, name
, age
, and single
. Therefore, a query that expects to extract people
must reference one or more of those properties. Since ScriptDb is agnostic about the objects you store in it, we use of the type
property as a convention to identify object types - and we do that in every query. We could just query for age
, but that could also find objects that aren't people
, which we aren't interested in.
function findOlderThan( age ) {
var db = ScriptDb.getMyDb();
var people = []; // array to hold results
// Find people with an age greater than given value.
var results = db.query({
type: 'person',
age: db.greaterThan(age)
});
while (results.hasNext()) {
var item = results.next();
people.push(item);
}
return people;
}
function test_findOlderThan() {
deleteAll(); // from developers.google.com/apps-script/guides/script-db/patterns#delete_all_items_in_the_database
loadDb();
Logger.log(JSON.stringify(findOlderThan(20))); // 3 results
Logger.log(JSON.stringify(findOlderThan(25))); // 2 results
Logger.log(JSON.stringify(findOlderThan(50))); // 1 result
Logger.log(JSON.stringify(findOlderThan(100))); // no result
}
function loadDb() {
var db = ScriptDb.getMyDb();
var item = db.save({
type: 'person',
name: 'fred',
town: 'Shelbyville',
age: 25,
single: true
});
item = db.save({
type: 'person',
name: 'joe',
town: 'Springfield',
age: 45,
single: false
});
item = db.save({
type: 'person',
name: 'sam',
town: 'Springfield',
age: 90,
single: true
});
}