Is there a generic approach to "compressing" nested objects to a single level:
var myObj = {
a: "hello",
b: {
c: "world"
}
}
compress(myObj) == {
a: "hello",
b_c: "world"
}
I guess there would be some recursion involved, but I figured I don't need to reinvent the wheel here... !?
Here's a quick one, but watch out, b/c it will not work w/ arrays and null values (b/c their typeof returns "object").
Here's a quick CoffeeScript version based off Matthew Crumley's answer (I didn't use
includePrototype
as I had no need for it):And a basic unflatten version, which would undoubtedly fail with repeated separators and other such trickiness:
FWIW, I use these functions to push object graphs into Redis hashes, which only support a single depth of key/value pairs.
You can include members inherited members by passing
true
into the second parameter.A few caveats:
recursive objects will not work. For example:
will recurse until it throws an exception.
Like ruquay's answer, this pulls out array elements just like normal object properties. If you want to keep arrays intact, add "
|| prop instanceof Array
" to the exceptions.If you call this on objects from a different window or frame, dates and regular expressions will not be included, since
instanceof
will not work properly. You can fix that by replacing it with the default toString method like this: