1

I have a dynamically generated, multi level nested object of UNIQUE values. I want to flatten it (using either AngularJS or vanilla JS) and create a simple array or object of each key / value. So if the object looks like this :

[ 

{name : "parent",
 age: 21,
 children: [
     { name : "child",
     dob: [{
         day: "01",
         month: "01",
         year : "82"
     }],
     children: [
     { 
        name : "grandchild",
        dob: [{
            day: "01",
            month: "01",
            year : "02"
            }]
      }
    ]
   }
 ]
}

];

The flattened object should look like this :

"name":"parent",
"age":21,
"children.name":"child",
"children.dob.day":"01",
"children.dob.month":"01",
"children.dob.year":"82",
"children.children.name":"grandchild",
"children.children.dob.day":"01",
"children.children.dob.month":"01",
"children.children.dob.year":"02"

I have found 2 functions to flatten an object, but both insert indexes next to every node. (0.children.0.children.0.dob.0.year) This is no use to me, and not necessary as my values are unique. I need the format above. You can see the functions i'm currently using in this codepen : https://codepen.io/anon/pen/qMXEmB

Can anyone help me remove those pesky "zeros" from my final object?

0

1 Answer 1

1

Brutal, but instead of

toReturn[i + '.' + x] = flatObject[x];

You can remove the 0s like so:

let index = i === "0" ? '' : i + '.';
toReturn[index + x] = flatObject[x];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.