Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created July 1, 2013 16:42
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 jpillora/5902477 to your computer and use it in GitHub Desktop.
Save jpillora/5902477 to your computer and use it in GitHub Desktop.
Flatten Object
//converts this:
//{ counters:
// { 'statsdbad_lines_seen': 0,
// 'statsdpackets_received': 98,
// bucket: 26 },
// timers: {},
// gauges: { gaugor: 303 },
// timer_data: {},
// counter_rates:
// { 'statsdbad_lines_seen': 0,
// 'statsdpackets_received': 9.8,
// bucket: 2.6 },
// sets: [ [ '5' ] ],
// pctThreshold: [ 90 ]
//}
//into this:
//counters.statsdbad_lines_seen=0
//counters.statsdpackets_received=98
//counters.bucket=26
//gauges.gaugor=303
//counter_rates.statsdbad_lines_seen=0
//counter_rates.statsdpackets_received=9.8
//counter_rates.bucket=2.6
//sets.0.0=5
//pctThreshold.0=90
var flatten = function(obj, line, lines) {
if(!lines) lines = [];
if(!line) line = '';
if(!_.isArray(obj) && !_.isObject(obj))
return lines.push(line + '=' + obj);
for(var k in obj)
flatten(obj[k],line+(line.length?'.':'')+k,lines);
return lines;
}
print(flatten(obj).join('\n'));
//TODO: dots and equals in keys need to be escaped...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment