Last active
August 29, 2015 14:26
-
-
Save ben-bradley/295e7d52e3a6bac2cbb2 to your computer and use it in GitHub Desktop.
Convert an object into a csv
This file contains hidden or 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
'use strict'; | |
var data = { | |
foo: 'bar', | |
baz: { | |
qux: 'zaq', | |
oof: 'rab' | |
} | |
}, | |
_ = require('lodash'); | |
function convert(src) { | |
var lines = [{ | |
src: src, | |
line: [] | |
}]; | |
return processLines(lines); | |
} | |
function processLines(lines) { | |
var line, results = []; | |
while (line = lines.shift()) { | |
if (_.isObject(line.src)) { | |
var keys = Object.keys(line.src); | |
for (var k in keys) { | |
var key = keys[k], | |
_line = line.line.concat([key]); | |
lines.push({ | |
src: line.src[key], | |
line: _line | |
}); | |
} | |
} else if (_.isString(line.src)) { | |
var _line = line.line.concat([line.src]); | |
results.push(_line); | |
} | |
} | |
return results.map(function(line) { | |
return line.join(); | |
}).join('\n'); | |
} | |
console.log(convert(mergedMap)); | |
/* | |
foo,bar | |
baz,qux,zaq | |
baz,oof,rab | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forgive the indentation. For some reason I couldn't get it to spaces/2 in Gist's UI