Last active
April 25, 2023 15:01
-
-
Save AnechaS/d37b648d844cfd7931166d151e814262 to your computer and use it in GitHub Desktop.
JavaScript Get object value by path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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