Last active
August 3, 2016 11:17
-
-
Save a-tarasyuk/904e059de5e9938ac7a48b0f6c5abb67 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| function isObject(value) { | |
| return typeof value === 'object' && value !== null; | |
| } | |
| function flatten(data, result = {}, prefix = '') { | |
| return Object | |
| .keys(data) | |
| .reduce(function (result, key) { | |
| const path = prefix ? `${ prefix }.${ key }` : key; | |
| if (isObject(data[key])) { | |
| return flatten(data[key], result, path); | |
| } | |
| result[path] = data[key]; | |
| return result; | |
| }, result); | |
| } | |
| // {x:1, y:1, z:{a:1,b:2}} flattens to {x:1, y:1, z.a:1, z.b: 2} | |
| var data = { | |
| x: 1, | |
| y: 1, | |
| z: { | |
| a: 1, | |
| b: 2, | |
| z: { | |
| x: 100, | |
| a: { | |
| a: 2 | |
| } | |
| } | |
| } | |
| }; | |
| console.log( | |
| flatten(data) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment