Is there a generic approach to \"compressing\" nested objects to a single level:
var myObj = {
a: \"hello\",
b: {
c: \"world\"
}
}
compress(
Here's a quick CoffeeScript version based off Matthew Crumley's answer (I didn't use includePrototype
as I had no need for it):
flatten = (obj, into = {}, prefix = '', sep = '_') ->
for own key, prop of obj
if typeof prop is 'object' and prop not instanceof Date and prop not instanceof RegExp
flatten prop, into, prefix + key + sep, sep
else
into[prefix + key] = prop
into
And a basic unflatten version, which would undoubtedly fail with repeated separators and other such trickiness:
unflatten = (obj, into = {}, sep = '_') ->
for own key, prop of obj
subKeys = key.split sep
sub = into
sub = (sub[subKey] or= {}) for subKey in subKeys[...-1]
sub[subKeys.pop()] = prop
into
FWIW, I use these functions to push object graphs into Redis hashes, which only support a single depth of key/value pairs.