0

Get nested objects data using a string selector

Function JavaScript 1 revisions 99 a year ago a year ago
function dig(obj, selector) {
	let result = obj;
	const splitter = selector.split('.');
	for (let i = 0; i < splitter.length; i++){
		if (result == undefined)
			return undefined;
			
		result = result[splitter[i]];
	}
	return result;
}

The basic idea is being able to have an object such as {a: {b: 1}} and be able to access b through a.b selector.

const obj = {a: 1, b: 2, c: {d: 3, e: {f: 6}}};

dig(obj, 'a');      // 1
dig(obj, 'b');      // 2
dig(obj, 'c');      // {d: 3, e: {…}}
dig(obj, 'c.e.f');  // 6
dig(obj, 'c.e');    // {f: 6}