Skip to content

Instantly share code, notes, and snippets.

@dkuppitz
Created April 28, 2012 11:29
Show Gist options
  • Save dkuppitz/2518160 to your computer and use it in GitHub Desktop.
Save dkuppitz/2518160 to your computer and use it in GitHub Desktop.
Flatten JSON objects
var flatten, obj;
flatten = require ('./flatten');
obj = {
foo: 'bar',
bar: 'foo',
foobar: {
foo: 'foo',
bar: 'bar'
}
};
console.log(flatten(obj));
/* RESULT:
{
'foo': 'bar',
'bar': 'foo',
'foobar.foo': 'foo',
'foobar.bar': 'bar'
}
*/
var flatten;
flatten = module.exports = function(obj, path, result) {
var key, val, _path;
path = path || [];
result = result || {};
for (key in obj) {
val = obj[key];
_path = path.concat([key]);
if (val instanceof Object) {
flatten(val, _path, result);
} else {
result[_path.join('.')] = val;
}
}
return result;
};
@pulkitsinghal
Copy link

Wow, thanks! I used it for coverting JSON entries to rows before outputting CSV file: ShoppinPal/vend-tools@b9c59fb ... tips hat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment