Created
April 28, 2012 11:29
-
-
Save dkuppitz/2518160 to your computer and use it in GitHub Desktop.
Flatten JSON objects
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
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' | |
} | |
*/ |
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
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, thanks! I used it for coverting JSON entries to rows before outputting CSV file: ShoppinPal/vend-tools@b9c59fb ... tips hat