Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 502
Combustion007 Avatar asked Mar 09 '26 08:03

Combustion007


1 Answers

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.

like image 54
Joe Avatar answered Mar 11 '26 08:03

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!