Created
June 19, 2014 15:09
-
-
Save geekman/c2c9463c4a1789474f13 to your computer and use it in GitHub Desktop.
flattens JS object hierarchies (used for shaping data for D3.js)
This file contains 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
// | |
// 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