JavaScriptFundamental (ES6), part 2
Pick nested fields by path in JavaScript
102 Pick a projection out of a nested object by path
fairGiven an order and a list of paths like customer.address.city, build a new object containing only those paths, rebuilding the nesting as it goes. A path that does not exist must be left out entirely rather than set to undefined, and a path that runs through null must not throw. Then look at what happens to an array index along the way.
Stuck? Three hints, smallest first
- 1.
path.split('.').reduce(...)walks down the object; guard each step againstnullandundefined. - 2. Writing needs the same walk in reverse: create a plain object for each missing level, then assign the last key.
- 3. Two paths sharing a prefix must merge into one branch, not overwrite it, which they do if you only create what is missing.
const getPath = (source, path) =>
path.split('.').reduce((node, key) => (node === null || node === undefined ? undefined : node[key]), source);
function setPath(target, path, value) {
const keys = path.split('.');
let node = target;
for (let i = 0; i < keys.length - 1; i++) {
if (node[keys[i]] === undefined) node[keys[i]] = {}; // only create what is missing
node = node[keys[i]];
}
node[keys[keys.length - 1]] = value;
return target;
}
function pick(source, paths) {
const out = {};
for (const path of paths) {
const value = getPath(source, path);
if (value !== undefined) setPath(out, path, value); // a miss leaves no key at all
}
return out;
}
const order = {
id: 'ORD-001',
status: 'paid',
totalKobo: 1290000,
customer: {
name: 'Adaeze Okonkwo',
phone: '08031234567',
address: { street: '14 Balogun Street', city: 'Lagos', lga: 'Ikeja' },
},
items: [
{ sku: 'GARI-5', name: 'Gari, 5kg', qty: 2 },
{ sku: 'OIL-1', name: 'Palm oil, 1L', qty: 1 },
],
courier: null,
};
const summary = pick(order, [
'id',
'customer.name',
'customer.address.city',
'courier.tracking',
'nowhere.at.all',
'items.0.name',
]);
const sharedBranch = pick(order, ['customer.address']);
const sameObject = sharedBranch.customer.address === order.customer.address;
const nothingAsked = pick(order, []);
const deepHit = getPath(order, 'customer.address.lga');
const deepMiss = getPath(order, 'customer.address.postcode');
const throughNull = getPath(order, 'courier.tracking.code');
console.log('summary :', summary);
console.log('shared leaf :', sameObject);
console.log('deep hit :', deepHit, '| deep miss:', deepMiss);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a top-level key is copied straight across', summary.id, 'ORD-001');
test('nested paths are rebuilt, and two of them sharing a prefix merge into one branch', summary.customer, { name: 'Adaeze Okonkwo', address: { city: 'Lagos' } });
test('a leaf object is shared by reference, so this is a projection and not a deep copy', sameObject, true);
test('a path running through null gives undefined rather than throwing, however deep', [throughNull, deepMiss], [undefined, undefined]);
test('and a path that missed leaves no key behind at all', [Object.keys(summary), 'courier' in summary, 'nowhere' in summary], [['id', 'customer', 'items'], false, false]);
test('an index in a path reads the array but writes a plain object, so the array shape is lost', summary.items, { 0: { name: 'Gari, 5kg' } });
test('asking for nothing gives an empty object rather than the whole thing', nothingAsked, {});
test('getPath on its own answers a deep hit and a deep miss the same way an optional chain would', [deepHit, order.customer?.address?.postcode], ['Ikeja', undefined]);
Two things make the writer correct. Creating a level only when it is undefined is what lets customer.name and customer.address.city both land in one customer object — assigning {} unconditionally would wipe whichever came first. And skipping the write entirely when the read produced undefined is what keeps a missing path out of the output; setting it explicitly gives you a key whose value is undefined, which serialises to null in JSON and shows up in the UI as an empty field that looks like real data.
The third assertion is the important limitation. This is a projection, not a clone: the leaf values are the same objects, so mutating summary.customer.address.city would change the order. That is usually what you want — it is cheap, and the projection is for reading — but it means a projection is not safe to hand to something that mutates. structuredClone is the answer when you need real isolation.
The sixth assertion is the trap in path-based writing. items.0.name reads perfectly well, because array['0'] is the same as array[0], but the writer has no way to know that 0 meant an array index, so it creates { '0': ... }. The output serialises as an object with a numeric key, and anything expecting to map over it breaks. Real implementations decide by looking at the key — all digits means create an array — which is a choice with its own surprise: a genuinely numeric object key then becomes an array index.