hughsk / flat

:steam_locomotive: Flatten/unflatten nested Javascript objects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possible to keep parent key

yashinnhl opened this issue · comments

Hi I want to keep parent key and all its children as stringified JSON, is it possible to do that with flatten?

Example

{
     a : 'blah',
     data : {
        a : 'sth',
        b: 'sth'
    }
}

expected output

{
a: 'blah', 
   data: `{
     a: sth,
     b: sth
   }`,
  data.a = sth,
  data.b = sth
}

I really appreciate if you can guide me here? Thanks

We can add key and value when isObject is true.

if (isobject) {
        // add first level keys example: data , data.object
        output[newKey] = value;
}

Hey @yashinnhl ! I'm also interested in this.
I'm not sure I understood your second comment! What do you mean by dictionary?

Hey @yashinnhl ! I'm also interested in this.
I'm not sure I understood your second comment! What do you mean by dictionary?

Hey @giorgosera I edited my comments. Sorry for confusion. In general, I mean we can keep first level keys just like an example even if they are object.
consider this :

ExampleObject:  {
 a : 'blah',
 data : {
   a : 'sth',
   b: 'sth'
 }
}

Can be converted to :

 {
  a: 'blah',
  data: { a: sth, b: sth },
  data.a = sth,
  data.b = sth
}

To achieve this, we need to add condition - if (isObject) - to the index, and output[newKey] = value will keep parent key for us.
For example, value = { a: sth, b: sth } will be assigned data key first and then flatten process will create data.a = sth, and data.b = sth.

I hope it helps. I am still not sure it is optimized or not but at least worked for me :).