Combustion007
Combustion007

Reputation: 474

How to read an object's properties while using a recursive function in Javascript?

I wonder if someone can point me into the right direction on this. When I have an object, I usually read its properties via FOR IN LOOP. And since I know what the properties are because I created the very object, I know what keys and their values are. I would like to know if there are any other ways such as recursive approach to read through an object and its properties.

So here is the object for an example:

var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});

As you can see, I have declared the mObj and within it, I have declared mArr as an Array. And then I am pushing three objects within mArr:

  1. id
  2. days
  3. colors

if I wanted to find out mArr length, I would write something like:

alert(mObj.mArr.length);

And if I wanted to loop through the object, I would have something like this:

for(var a in mObj.mArr[0])
{
   alert(mObj.mArr[0][a]);
}

I wonder if I can just right one function and pass the parent object which happens to be "mObj" here, and this recursive function would through the "mObj" and list all of its properties from head to toe.

I would appreciate any input on this, please.

Thanks a lot.

Upvotes: 2

Views: 5466

Answers (1)

Joe
Joe

Reputation: 82654

Here's a basic example:

var mObj = {};
mObj.mArr = [];
mObj.mArr.push({id:['id1','id2','id3']});
mObj.mArr.push({days:['Monday','Tuesday','Wednesday','Thursday']});
mObj.mArr.push({colors:['orange','red','blue','green','yellow','white']});

function r(obj) {
    if (obj)
        for (var key in obj) {
            if (typeof obj[key] == "object")
                r(obj[key]);
            else if (typeof obj[key] != "function")
                console.log(obj[key])
        }

    return;
} 

r(mObj);

if there is an object not a function call the function again, else console log the value if it is not a function.

Upvotes: 17

Related Questions