Implement get and set by Path From Scratch in JavaScript
Write get and set by path from scratch in JavaScript, with dotted and bracket paths, defaults, array creation, immutable updates and safe keys. Node.js 24.

Reading user.address.city fails with a TypeError the moment address is missing, and that one annoyance produced _.get and _.set, two of the most copied utilities in JavaScript. They take a path such as "a.b[0].c" and walk a value along it. The interview version asks you to parse the path, return a default for missing values, create the intermediate objects and arrays when setting and avoid corrupting anything on the way. Optional chaining solved the reading half for fixed paths, so the remaining case is a path held in a variable. This post builds both functions on Node.js 24, with a parser, a mutating set, an immutable variant and the checks that keep set safe. For the sibling problem of combining two objects, see implementing a deep merge.
The contract
get(object, path, fallback) returns the value at the path, or fallback if any step is missing. set(object, path, value) writes the value, creating any missing parents, and returns the object. A path is a string such as "a.b[0].c" or an array of keys such as ["a", "b", 0, "c"].
Parsing the path
Normalize every path into an array of keys first. Everything after that is a loop over an array.
function toPath(path) {
if (Array.isArray(path)) return path.map(String);
const keys = [];
path.replace(/[^.[\]]+|\[(?:(-?\d+)|(["'])(.*?)\2)\]/g, (match, index, quote, text) => {
keys.push(index ?? text ?? match);
return match;
});
return keys;
}
console.log(toPath("a.b[0].c"));
console.log(toPath('a["x.y"].z'));
console.log(toPath(["a", 1]));
console.log(toPath(""));[ 'a', 'b', '0', 'c' ]
[ 'a', 'x.y', 'z' ]
[ 'a', '1' ]
[]The regular expression has two alternatives. [^.[\]]+ matches a run of characters that are not a dot or a bracket, which is a plain key. The second alternative matches a bracket expression: either digits for an index, or a quoted string, where the backreference \2 makes the closing quote match the opening one. Quoting is how a key that contains a dot, such as "x.y", is expressed. String.prototype.replace is used here only to loop over matches with their groups. Newer code might use matchAll, which says what it means.
Keys are strings, including indexes. That is not a problem, since array["0"] and array[0] read the same element, and keeping everything a string simplifies the rest.
get
function get(object, path, fallback) {
let current = object;
for (const key of toPath(path)) {
if (current === null || current === undefined) {
return fallback;
}
current = current[key];
}
return current === undefined ? fallback : current;
}
const data = { user: { name: "Ada", tags: ["x", "y"], age: 0, nick: null } };
console.log(get(data, "user.name"));
console.log(get(data, "user.tags[1]"));
console.log(get(data, "user.address.city", "unknown"));
console.log(get(data, "user.age", 99));
console.log(get(data, "user.nick", "none"));Ada
y
unknown
0
nullLook at the last two lines. The fallback applies only when the result is undefined, so a stored 0 is returned and so is a stored null. That mirrors Lodash, and it is a decision: some people expect null to trigger the default. If you want that, replace the final check with current ?? fallback. Whichever you choose, say so, because it is the thing someone will ask about.
The check at the top of the loop is what makes a missing parent safe. Reading a property of undefined throws, so the function stops one step early and returns the fallback. A primitive is not null, so get({ a: "text" }, "a.length") reads the length of the string and returns 4: primitives have properties, and walking into them is legal.
set
Walking is the same, but when a key is missing, create the container. The container type depends on the next key: an index means an array, anything else means an object.
const isIndex = (key) => /^(0|[1-9]\d*)$/.test(key);
function set(object, path, value) {
const keys = toPath(path);
if (keys.length === 0) return object;
let current = object;
for (let i = 0; i < keys.length - 1; i += 1) {
const key = keys[i];
const next = current[key];
if (next === null || typeof next !== "object") {
current[key] = isIndex(keys[i + 1]) ? [] : {};
}
current = current[key];
}
current[keys[keys.length - 1]] = value;
return object;
}
const target = {};
set(target, "a.b[1].c", "deep");
set(target, "list[2]", "x");
console.log(JSON.stringify(target));
console.log(target.a.b);
console.log(target.list);{"a":{"b":[null,{"c":"deep"}]},"list":[null,null,"x"]}
[ <1 empty item>, { c: 'deep' } ]
[ <2 empty items>, 'x' ]The first call creates a as an object because b is not an index, then b as an array because the next key is 1, then an object at index 1 for c. Index 0 of b is never written, so the array has a hole, shown as <1 empty item> by Node.js and serialized as null by JSON.stringify. The second call shows the same for list. Holes are legal and rarely what anyone wants, so decide whether to fill them.
The test isIndex accepts 0 and numbers without leading zeros, so "007" is treated as an object key, not an array position. That keeps a key like a zero-padded id from turning into an array with seven empty slots.
An existing non-object value in the way is overwritten: set({ a: 1 }, "a.b", 2) replaces 1 with { b: 2 }. Overwriting silently is the Lodash behavior. A stricter version throws, which is safer for configuration code.
The prototype pollution guard
The same hazard from deep merging applies here, and more directly, since the path is a string from outside.
const victim = {};
set(victim, "__proto__.polluted", "yes");
console.log({}.polluted);
delete Object.prototype.polluted;yesWalking __proto__ from a plain object reaches Object.prototype, and the final assignment writes onto it. Every object in the program now has the property. The guard is to reject the dangerous keys before walking.
const FORBIDDEN = new Set(["__proto__", "prototype", "constructor"]);
function safeSet(object, path, value) {
const keys = toPath(path);
if (keys.some((key) => FORBIDDEN.has(key))) {
throw new Error(`unsafe key in path: ${keys.join(".")}`);
}
return set(object, keys, value);
}
try {
safeSet({}, "__proto__.polluted", "yes");
} catch (error) {
console.log(error.message);
}
console.log({}.polluted);unsafe key in path: __proto__.polluted
undefinedThrowing is better than silently ignoring: a path with __proto__ in it is either a bug or an attack, and the caller should hear about it. For get, the risk is reading, not writing, but exposing constructor lets a path reach Function, so apply the same check or restrict the walk to own properties with Object.hasOwn.
An immutable set
State libraries and React code want to change a path without modifying the original. Copy each container along the path and share everything else.
function setIn(object, path, value) {
const keys = toPath(path);
if (keys.length === 0) return value;
const [key, ...rest] = keys;
const child = object?.[key];
const nextValue =
rest.length === 0
? value
: setIn(child !== null && typeof child === "object" ? child : isIndex(rest[0]) ? [] : {}, rest, value);
const copy = Array.isArray(object) ? [...object] : { ...object };
copy[key] = nextValue;
return copy;
}
const before = { user: { name: "Ada", roles: ["admin"] }, theme: { dark: true } };
const after = setIn(before, "user.name", "Linus");
console.log(after.user.name, before.user.name);
console.log(after.theme === before.theme);
console.log(after.user.roles === before.user.roles);Linus Ada
true
trueThe new tree has a new root and a new user, since those are on the path, while theme and roles are the same objects as before. Sharing the untouched parts is called structural sharing, and it is what makes equality checks by reference cheap: after.theme === before.theme tells a UI that nothing under theme changed, with no deep comparison.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("get reads nested and bracket paths", () => {
assert.equal(get({ a: [{ b: 5 }] }, "a[0].b"), 5);
assert.equal(get({}, "a.b.c", "x"), "x");
});
test("get keeps falsy values", () => {
assert.equal(get({ n: 0 }, "n", 9), 0);
});
test("set creates arrays and objects", () => {
assert.deepEqual(set({}, "a[0].b", 1), { a: [{ b: 1 }] });
});
test("setIn leaves the original unchanged", () => {
const original = { a: { b: 1 } };
const updated = setIn(original, "a.b", 2);
assert.equal(original.a.b, 1);
assert.equal(updated.a.b, 2);
});
test("safeSet rejects __proto__", () => {
assert.throws(() => safeSet({}, "__proto__.x", 1), /unsafe key/);
});ℹ tests 5
ℹ pass 5
ℹ fail 0Deleting and checking a path
Two companions follow naturally. has(object, path) answers whether the path exists, which is different from get returning undefined: a key can exist and hold undefined. Walk the same way, but test each step with Object.hasOwn and return false as soon as one is missing. And unset(object, path) walks to the parent and uses delete on the last key. For arrays, delete leaves a hole and keeps the length, so a careful version uses splice when the parent is an array and the key is an index.
Both need the same prototype guard as set, since a path such as __proto__.toString would otherwise delete a method from every object in the program. Writing the guard once, in toPath or in a shared helper called by all four functions, is better than repeating it, because the function that forgets it is the one that gets exploited.
Where optional chaining fits
For a path known at write time, user?.address?.city ?? "unknown" is shorter, faster to read and checked by editors and type checkers. A string path earns its place only when the path is data: a field name from a form definition, a column in a configuration table or a rule stored in a database. In TypeScript, string paths also lose type safety unless you build a template-literal type for them, which is one more reason to prefer the operator whenever the path is fixed.


