Last active
August 29, 2015 14:14
-
-
Save dgowrie/38d2cc872718c4ccf109 to your computer and use it in GitHub Desktop.
How to recursively flatten a nested hash (object literal) in JavaScript.
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
| // alternative approach for testing if value is an Object | |
| (function() { | |
| 'use strict'; | |
| var hash = { | |
| level1a: 'l1a', | |
| level1b: 'l1b', | |
| level1c: { | |
| level2a: 'l2a', | |
| level2b: { | |
| level3a: 'l3a' | |
| }, | |
| level2c: 'l2c' | |
| }, | |
| level1d: 'l1d' | |
| }; | |
| var x = 1, | |
| flat = {}; | |
| function flatten(nested) { | |
| for (var key in nested) { | |
| if ( isObj(nested[key]) ) { | |
| console.log('nested ', nested[key]); | |
| flatten(nested[key]); | |
| } else { | |
| flat['prop' + x] = nested[key]; | |
| x++; | |
| } | |
| } | |
| return flat; | |
| } | |
| function isObj(obj) { | |
| return obj === Object(obj); | |
| } | |
| console.log(flatten(hash)); | |
| }()); |
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
| // How to recursively flatten a nested hash (object literal) in JavaScript. | |
| (function() { | |
| 'use strict'; | |
| var nestedObj = { | |
| key1: 'k1', | |
| key2: 'k2', | |
| key3: { | |
| k3a: 'nested-k3a', | |
| k3b: 'nested-k3b' | |
| }, | |
| key4: { | |
| k4a: { | |
| k4a1: 'doublenested-k4a' | |
| }, | |
| k4b: 'nested-k4b' | |
| }, | |
| key5: 'k5' | |
| }, | |
| flat = {}, | |
| x = 0; | |
| function flatten(obj) { | |
| //console.log('object being worked on: ', obj); | |
| for (var key in obj) { | |
| if (obj[key].constructor === Object) { | |
| //console.log('nested object found: '); | |
| flatten(obj[key]); | |
| } else { | |
| flat['prop-' + x] = obj[key]; | |
| //console.log('flat is now: ', flat); | |
| x++; | |
| } | |
| } | |
| } | |
| flatten(nestedObj); | |
| console.log('totally flat: ', flat); | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment