Created
February 10, 2015 18:38
-
-
Save joshblack/a28f4e7144ad41df8025 to your computer and use it in GitHub Desktop.
Grab all the data nodes of an Object
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
var assign = require('object-assign'); | |
// Get all the data nodes of an object | |
function flatten(obj) { | |
return Object.keys(obj).reduce(function (prev, key) { | |
return isObject(obj[key]) | |
? assign(prev, flatten(obj[key])) | |
: (prev[key] = obj[key], prev); | |
}, {}); | |
} | |
function isObject(obj) { | |
return Object.prototype.toString.call(obj) == '[object Object]'; | |
} | |
var flat3 = flatten({ val1: 1, level2: { val2: 2 } }); | |
var flat4 = flatten({ | |
val1: 1, | |
level2: { | |
val2: 2 | |
}, | |
level3: { | |
nested: { | |
val3: 3 | |
} | |
}, | |
level4: { | |
nested: { | |
nested: { | |
val4: 4 | |
} | |
} | |
} | |
}); | |
console.log(flat3); //=> { val1: 1, val2: 2 } | |
console.log(flat4); //=> { val1: 1, val2: 2, val3: 3, val4: 4 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment