Created
November 21, 2016 23:37
-
-
Save john4/1845ec068a8ac29e2d80bc065921ba6f to your computer and use it in GitHub Desktop.
ES6 flatten object function
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
// { | |
// foo: { | |
// bar: "0", | |
// baz: { | |
// hello: "world" | |
// } | |
// } | |
// } | |
// ...becomes... | |
// { | |
// foo/bar: "0", | |
// foo/baz/hello: "world" | |
// } | |
function flattenObject (obj) { | |
let result = {} | |
for (let key of Object.keys(obj)) { | |
let val = obj[key] | |
// recur | |
if (typeof val == 'object' && val !== null && val.constructor == Object) { | |
let flattened = flattenObject(val) | |
for (let flatKey of Object.keys(flattened)) { | |
result[key + '/' + flatKey] = flattened[flatKey] | |
} | |
} | |
// base | |
else { | |
result[key] = val | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment