Given I have a javascript object, is there a way to iterate over all the primitive subproperties?
For instance, if I have an object
{
foo: 17,
bar: {
a: 2,
b: 7
}
}
I would like to iterate over foo, bar.a, and bar.b.
Please keep in mind I prefer to iterate over Object.keys() rather than using a for/in loop, although I’m sure I could translate any for/in loop responses into an Object.keys() iteration.
You can use a recursive function like this:
Which generates the output:
A note on this function. It recurses over anything that is an object. For instance, if you had an array in the object, you would get separate lines for each item in the array.
So for the following object:
The output would appear:
There are obviously ways to handle this, but you will need to tailor the function to meet your requirements.