Skip to content

Instantly share code, notes, and snippets.

@joshblack
Created February 10, 2015 18:38
Show Gist options
  • Save joshblack/a28f4e7144ad41df8025 to your computer and use it in GitHub Desktop.
Save joshblack/a28f4e7144ad41df8025 to your computer and use it in GitHub Desktop.
Grab all the data nodes of an Object
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