Reference · Maps
get
signature
get(map | null, any, any=) -> anyWhat it does
The value under a key, or the default when the key is not in the map; without a
default, null. The key is turned into text first, as all map keys are, so
get(m, 5) reads m["5"]. It is m[k] as a function, useful in a pipeline and when
the map may be null.
Examples
let user = { name: "Ann", age: 41 }print(get(user, "name"), get(user, "email"), get(user, "email", "none"))print(get(user, "age") + 1)output
Ann null none42Edge cases
- The default is for a missing key only: a key whose value is
nullgivesnull, not the default.??aftergetcovers both. - Keys are text:
get(m, 5)andget(m, "5")read the same entry; a decimal key is read without its trailing zeros, so1.50mfinds"1.5". - A
nullmap is an empty map:get(null, k, d)isd, not an error. - An error value as the key is given back, not the default: it is no key (its text was
taken for one), so
int(id)that failed is not looked up aserr(...).
let m = { a: null, "5": "five", "1.5": "x" }print(get(m, "a", 0), get(m, "a") ?? 0)print(get(m, 5), get(m, 1.50m))print(get(null, "a"), get(null, "a", "dflt"))print(get(m, int("q"), "dflt"))output
null 0five xnull dflterr("not an int: \"q\"")Errors
A map that is a list, a string or a number is a runtime error, not an error value.
For a list use xs[i], first or slice.
this one fails
print(get([1, 2], 0))output
line 1: `get` expects a map as argument 1, got listChaining
In a pipeline the map comes first, so get takes the key as its argument:
print(`{"a": 1}` | json.parse | get("a"))let counts = ["x", "y", "x"] | reduce({}, (acc, w) => set(acc, w, get(acc, w, 0) + 1))print(counts)output
1{ x: 2, y: 1 }See also
Thread
Thread 0 posts
On get(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo