Skip to content

Instantly share code, notes, and snippets.

@geekman
Created June 19, 2014 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekman/c2c9463c4a1789474f13 to your computer and use it in GitHub Desktop.
Save geekman/c2c9463c4a1789474f13 to your computer and use it in GitHub Desktop.
flattens JS object hierarchies (used for shaping data for D3.js)
//
// flattens object hierarchies like {'US': {'AZ': {size: 999, ...} } }
// into array of "rows" like {country: 'US', state: 'AZ': size: 999, ...}
// e.g. flatten(data, 2, ['country', 'state'])
//
// values can also form another level like so:
// e.g. flatten(data, 3, ['country', 'state', 'stat'])
// which produces: {country: 'US', state: 'AZ', stat: 'size', value: 999}
//
// NOTE: modifies objects directly, so don't run multiple times with diff levels
//
function flatten(obj, level, keys) {
var keyname = keys.length > 0 ? keys[0] : null;
if (level == 0) {
if (!obj || obj.constructor != Object) {
var obj2 = {};
obj2[keyname || 'value'] = obj;
obj = obj2;
}
return [obj];
} else {
var arr = [];
for (var k in obj) {
flatten(obj[k], level - 1, keys.slice(1))
.forEach(function(o) {
o[keyname] = k;
arr.push(o);
});
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment