Last active
December 8, 2019 10:53
-
-
Save nombrekeff/7cc1711b20b6738b7d5e47b9acef32b5 to your computer and use it in GitHub Desktop.
Get all path from an object
This file contains 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
/** | |
* returns an array containing all paths to a value other than an object | |
* @param {object} obj | |
*/ | |
function flattenObject(obj) { | |
if (typeof obj !== 'object') { | |
return []; | |
} | |
let paths = []; | |
for (let key in obj) { | |
let val = obj[key]; | |
if (typeof val === 'object') { | |
let subPaths = flattenObject(val); | |
subPaths.forEach(e => { | |
paths.push({ | |
path: [key, e.path].join('.'), | |
value: e.value | |
}); | |
}); | |
} else { | |
let path = { path: key, value: val }; | |
paths.push(path); | |
} | |
} | |
return paths; | |
} | |
// Usage | |
flattenObject({ data: { name: 'john' } }); // res -> [{ path: 'data.name', value: 'john' }] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment