Created
July 7, 2017 12:39
-
-
Save jonataswalker/b0d9065adb876febec96a8c9fbd7dce7 to your computer and use it in GitHub Desktop.
Get Flat 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
// 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