JavaScriptFundamental (ES6), part 1
Get and set nested values by path in JavaScript
93 get and set by dotted path
fairWrite getPath(obj, 'buyer.address.lga', fallback) that walks a dotted string without throwing on a missing branch, and setPath(obj, path, value) that creates the objects it needs on the way down, choosing an array when the next segment is a number. Then find the two paths that cannot mean what they look like.
Stuck? Three hints, smallest first
- 1.
split('.')gives the segments; afor...ofthat reassigns a cursor walks them. - 2. Bail out the moment the cursor is
nullorundefined, before you index into it. That is the whole difference fromobj.a.b.cthrowing. - 3. For
set, the last segment is the one you assign to, sopopit off a copy of the list first. What to create for a missing segment depends on the segment after it.
const looksLikeIndex = (key) => String(Number(key)) === String(key) && Number(key) >= 0;
const getPath = (obj, path, fallback) => {
const keys = Array.isArray(path) ? path : String(path).split('.');
let cursor = obj;
for (const key of keys) {
if (cursor === null || cursor === undefined) return fallback;
cursor = cursor[key];
}
return cursor === undefined ? fallback : cursor;
};
const setPath = (obj, path, value) => {
const keys = Array.isArray(path) ? [...path] : String(path).split('.');
const leaf = keys.pop();
let cursor = obj;
for (const [i, key] of keys.entries()) {
const next = cursor[key];
if (next === null || typeof next !== 'object') {
cursor[key] = looksLikeIndex(keys[i + 1] ?? leaf) ? [] : {};
}
cursor = cursor[key];
}
cursor[leaf] = value;
return obj;
};
const order = {
id: 'ORD-771',
buyer: { name: 'Amaka', address: { lga: 'Yaba', city: 'Lagos' } },
lines: [{ sku: 'GRP-1', units: 2 }, { sku: 'GRP-2', units: 1 }],
};
const hollow = { a: { b: undefined } };
const odd = { 'buyer.name': 'Ngozi' };
const built = setPath({}, 'vendor.contact.phone', '0803 000 0000');
const withArray = setPath({}, 'lines.0.sku', 'GRP-9');
const target = { buyer: { address: { lga: 'Yaba' } } };
const returned = setPath(target, 'buyer.address.lga', 'Surulere');
console.log('get :', getPath(order, 'buyer.address.lga'), '| missing:', getPath(order, 'buyer.bank.name', 'unknown'));
console.log('index :', getPath(order, 'lines.1.sku'));
console.log('built :', built, '| array:', withArray);
console.log('dotted key:', getPath(odd, 'buyer.name', 'missing'), getPath(odd, ['buyer.name'], 'missing'));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a dotted path walks down the object', getPath(order, 'buyer.address.lga'), 'Yaba');
test('a missing branch returns the fallback instead of throwing', getPath(order, 'buyer.bank.name', 'unknown'), 'unknown');
test('a numeric segment indexes an array, because obj[1] and obj["1"] are one key', getPath(order, 'lines.1.sku'), 'GRP-2');
test('a leaf that exists and holds undefined gets the fallback too', [getPath(hollow, 'a.b', 'fallback'), Object.hasOwn(hollow.a, 'b')], ['fallback', true]);
test('set fills in the objects it needs on the way down', [built.vendor.contact.phone, Object.keys(built)], ['0803 000 0000', ['vendor']]);
test('a numeric next segment makes an array, not an object with a "0" key', [Array.isArray(withArray.lines), withArray.lines.length, withArray.lines[0].sku], [true, 1, 'GRP-9']);
test('set mutates in place and hands back the same object', [returned === target, target.buyer.address.lga], [true, 'Surulere']);
test('a key containing a dot is unreachable by string, reachable by array', [getPath(odd, 'buyer.name', 'missing'), getPath(odd, ['buyer.name'], 'missing')], ['missing', 'Ngozi']);
test('an empty path is one empty segment, not "the whole object"', getPath(order, '', 'nothing'), 'nothing');
Optional chaining already does the safe read: order?.buyer?.address?.lga. The reason a path helper still exists is that the path is data — it came from a config file, a form field name, a column definition — and you cannot write ?. against a string you have not seen yet. That is the only case where this beats the syntax.
Two design decisions are worth naming. Returning the fallback for a leaf that genuinely holds undefined is a lie about the data, and it is the behaviour every library ships, because the alternative needs two return values. And set creating branches is convenient right up to the moment a typo in a path silently grows a new object where you expected an error.
The dotted-key assertion is the real limit. A dotted string is a lossy encoding of a key list: any key with a dot in it becomes unreachable, and no amount of escaping fixes it cleanly. Accepting an array as well as a string, as this one does, costs one line and makes the awkward case expressible.