Created
January 17, 2022 19:34
-
-
Save victor141516/a46587144eaad84ee7e58563b9abf5cf to your computer and use it in GitHub Desktop.
Returns an object with the same structure as obj but each value is the path to the key
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
/** | |
* | |
* @param {any} obj The input object | |
* @param {string[]} exceptions List of keys not to convert | |
* @param {string} basePath Base string to use for the path | |
* @returns {any} Returns an object with the same structure as obj but each value is the path to the key | |
* @example pathize({a: {b: {c: 2}}, d: 3, e: 4}, ['e'], 'base') ==> {a: {b: {c: 'base.a.b.c'}}, d: 'base.a.d', e: 4} | |
*/ | |
function pathize(obj, exceptions = [], basePath = '') { | |
const clone = JSON.parse(JSON.stringify(obj)) | |
const w = (o, base) => { | |
Object.keys(o).map((k) => { | |
if ([Array, Object].includes(o[k]?.constructor)) { | |
w(o[k], (base ? base + '.' : '') + k) | |
} else { | |
if (!exceptions.includes(k)) o[k] = (base ? base + '.' : '') + k | |
} | |
}) | |
} | |
w(clone, basePath) | |
return clone | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment