Skip to content

Back to Snippets

keyPathValue()

Modeled around the JavaScript optional chaining operator, getKeyPathValue() returns undefined if it finds any null or undefined values along the way.

The function sacrifices some performance for brevity. Use it when the key path is dynamic, otherwise prefer the native chaining operator.

/*
	Return the value of a nested key path from the object `obj`.
	The `keyPath` can be string of dot-separated key segments,
	or an array of keys.
*/
export function getKeyPathValue(obj, keyPath = []) {
	const parts = typeof keyPath === 'string' ? 
		keyPath.split('.') : 
		keyPath.slice();
	return parts.reduce((curr, key) => curr?.[key], obj);
}

The equivalent setter creates nested objects as needed.

export function setKeyPathValue(obj, keyPath = [], value) {
	let parts = typeof keyPath === 'string' ? 
		keyPath.split('.') : 
		keyPath.slice();
	let curr = obj;
	let part;
	while (parts.length > 1) {
		part = parts.shift();
		curr[part] = curr[part] ?? {};
		curr = curr[part];
	}
	if (parts.length) {
		curr[parts.shift()] = value;
	}
}