Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get Flat Object
// Turns
{
inputQueryId: 'gcd-input-query',
cssClasses: {
namespace: 'ol-geocoder',
spin: 'gcd-pseudo-rotate'
glass: {
container: 'gcd-gl-container'
}
}
// Into
{
inputQueryId: 'gcd-input-query',
cssClasses_namespace: 'ol-geocoder',
cssClasses_spin: 'gcd-pseudo-rotate',
cssClasses_glass_container: 'gcd-gl-container'
}
function getFlatVars(obj, prev = []) {
return Object.keys(obj).reduce((acc, curr) => {
if (typeof obj[curr] === 'object') {
prev.push(curr);
const flat = getFlatVars(obj[curr], prev);
Object.keys(flat).forEach(k => { acc[k] = flat[k] });
} else {
if (prev.length) {
acc[`${prev.join('_')}_${curr}`] = obj[curr];
} else {
acc[curr] = obj[curr];
}
}
return acc;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment