_.get(object, path, [defaultValue])
from Lodash lets you safely retrieve a deeply-nested property.
Re-implement this behaviour as a standalone get
function.
function get<T, R = unknown>(
object: T,
path: string | Array<string | number>,
defaultValue?: R
): R | unknown
path
accepts either"a.b[0].c"
), or["a", "b", 0, "c"]
).undefined
, return defaultValue
(or undefined
if no default provided).defaultValue
.["a.b"]
).const obj = {
a: { b: [{ c: 3 }] },
x: 0,
};
get(obj, "a.b[0].c"); // 3
get(obj, ["a", "b", 0, "c"]); // 3
get(obj, "a.b[1].c", "missing"); // "missing"
get(obj, "x.y.z", null); // null