Skip to content

Instantly share code, notes, and snippets.

@AnechaS
Last active April 25, 2023 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnechaS/d37b648d844cfd7931166d151e814262 to your computer and use it in GitHub Desktop.
Save AnechaS/d37b648d844cfd7931166d151e814262 to your computer and use it in GitHub Desktop.
JavaScript Get object value by path
/**
* Get the object value by path
* @param {object} obj
* @param {string} path
* @return {any}
* @example
* getObjectValue({ str: 'string', int: 0 }, 'str'); //=> 'string'
* getObjectValue({ obj: { str: 'string', int: 0 } }, 'obj.str'); //=> 'string'
* getObjectValue({ arr: [{ str: 'string', int: 0 }] }, 'obj[0].str'); //=> 'string'
* getObjectValue({ arr: [{ str: 'string', int: 0 }] }, 'obj[*].str'); //=> ['string']
*/
function getObjectValue(obj, path) {
try {
const segments = path.split('.');
let result = obj;
for (const [index, segment] of segments.entries()) {
const matches = /^(\w+)?\[(\d+|\*)\]$/.exec(segment);
if (!matches) {
result = result[segment];
continue;
}
const [_inp, k, i] = matches;
if (k !== undefined) {
result = result[k];
}
if (i === '*') {
const arr = segments.slice(index + 1);
const p = arr.join('.');
// return undefined when arr[0] is empty
if (typeof arr[0] === 'string' && !arr[0].trim().length) {
throw new Error('Invalid path');
}
const values = result.map((v) => p ? getObjectValue(v, p) : v);
const isValueEmpty = values.every((v) => v === undefined);
result = !isValueEmpty ? values : undefined;
break;
}
result = result[i];
}
return result;
} catch (error) {
return undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment