Reference · Maps

get

signature
get(map | null, any, any=) -> any

What 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 none42

Edge cases

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 list

Chaining

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

has, set, keys, values, merge

Thread
7Useful? Like it, or add to its thread below.

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