Overview
Implement select(data, selector) that queries nested data using a dot-separated path supporting:
a.b— nested property accessa[0]— array index accessa.*.b— wildcard (all children)
Examples
select({ a: { b: 1 }}, 'a.b'); // 1
select({ items: [{ name: 'a' }, { name: 'b' }]}, 'items.*.name'); // ['a','b']Solution
Reveal solution
function select(data, selector) {
const parts = selector.replace(/\[(\d+)\]/g, '.$1').split('.');
function recurse(obj, idx) {
if (idx === parts.length) return obj;
if (obj === null || obj === undefined) return undefined;
const part = parts[idx];
if (part === '*') {
const values = Array.isArray(obj) ? obj : Object.values(obj);
const results = values.map(v => recurse(v, idx + 1)).filter(v => v !== undefined);
return results;
}
const key = /^\d+$/.test(part) ? Number(part) : part;
return recurse(obj[key], idx + 1);
}
return recurse(data, 0);
}data-selection.js
Data Selection
hardcodingJavaScriptObjects
Overview
Implement select(data, selector) that queries nested data using a dot-separated path supporting:
a.b— nested property accessa[0]— array index accessa.*.b— wildcard (all children)
Examples
select({ a: { b: 1 }}, 'a.b'); // 1
select({ items: [{ name: 'a' }, { name: 'b' }]}, 'items.*.name'); // ['a','b']Solution
Reveal solution
function select(data, selector) {
const parts = selector.replace(/\[(\d+)\]/g, '.$1').split('.');
function recurse(obj, idx) {
if (idx === parts.length) return obj;
if (obj === null || obj === undefined) return undefined;
const part = parts[idx];
if (part === '*') {
const values = Array.isArray(obj) ? obj : Object.values(obj);
const results = values.map(v => recurse(v, idx + 1)).filter(v => v !== undefined);
return results;
}
const key = /^\d+$/.test(part) ? Number(part) : part;
return recurse(obj[key], idx + 1);
}
return recurse(data, 0);
}NameTopicDifficulty
103 of 103 problems