Skip to content

Instantly share code, notes, and snippets.

@nombrekeff
Last active December 8, 2019 10:53
Show Gist options
  • Save nombrekeff/7cc1711b20b6738b7d5e47b9acef32b5 to your computer and use it in GitHub Desktop.
Save nombrekeff/7cc1711b20b6738b7d5e47b9acef32b5 to your computer and use it in GitHub Desktop.
Get all path from an object
/**
* 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