hughsk / flat

:steam_locomotive: Flatten/unflatten nested Javascript objects
BSD 3-Clause "New" or "Revised" License
1.78k stars 195 forks source link

Blank array not flattened! #66

Open shishir99111 opened 6 years ago

shishir99111 commented 6 years ago

I'm using flat module for preparing object to store data in Redis DB. (Redis doesn't allow array and nested object ) Now, the Issue is Flat doesn't do anything to blank array.
E.g.

{
    a: [],
    a1: {
        a11: 1
    }
    b: 'test',
    c: 12
}
is flatten to 
{
    a: [],
    a1.a11: 1,
    b: "test",
    c: 12,
}

this gives me error on Redis. Can Flat module help me with this?

aecepoglu commented 6 years ago

And what should flat do instead? Remove the empty array?

shishir99111 commented 6 years ago

@aecepoglu not sure whether this module is intended to achieve it or not. But, I required my JSON Object should be flat (no nesting of object, no array inside the object. not even if it is blank). So, i think there should be a notation which will point as blank object and a blank array.

edosssa commented 6 years ago

I know I'm a a little late to the party. @shishir99111 I don't think Flat is supposed to do that. It does what it's supposed to do - flatten objects, and not remove empty arrays from flattened objects. If you don't want empty arrays in your flattened object (for some reason), it's left to you to cycle through the flattened object and perhaps delete properties whose values are arrays. P.s. if you don't want arrays so bad, why'd you include them in the original object in the first place? :)

lucas-rudd commented 6 years ago

I've opened up a similar issue regarding this. Flatten does the same thing with empty objects, where a is an object instead of an array.

Because of this, the object returned is not 'flattened', as an empty object is still nested within the original object.

This is causing us some issues as well, and we have written code to go through and remove these (they aren't needed in our specific case) but that means we cannot unflatten the resulted object to its original state.

A better solution may be to do something like

{
    a: '[Object|Array],
    a1.a11: 1,
    b: "test",
    c: 12,
}

or

{
    a: '[Object|Object]',
    a1.a11: 1,
    b: "test",
    c: 12,
}

to indicate that we have an empty object/array.

This is an odd case, because it requires some semi-unique value to indicate that the unflattened object should contain an empty nested object/array, rather than interpreting the string literally. In which case, if your original object had a literal string which was '[Object|Array]' for whatever reason, it would get converted to an array in the unflattening process, which is not what we would want.

Regardless, in order to fully 'flatten' an object, empty objects must also be flattened in the process.