Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.