Is there a good way to iterate over all the sub-tasks of a Javascript object?

Given that I have a javascript object, is there a way to iterate over all the primitive sub-properties?

For example, 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 that I prefer to iterate over Object.keys () instead of using a for / in loop, although I'm sure I could translate any answers for in / in into Object.keys () iteration.

+3


source to share


2 answers


You can use a recursive function like this:

var x = {
    foo: 17,
    bar: {
        a: 2,
        b: 7
    }
}

function parseObject(something) {
    var keys = Object.keys(something);
    for (var i = 0; i < keys.length; i++) {
        if (typeof something[keys[i]] === 'object') parseObject(something[keys[i]])
        else console.log(keys[i] + " : " + something[keys[i]]);
    }
}
parseObject(x);

      

Which generates the output:

foo : 17 
a : 2 
b : 7 

      

A note about this function. It rewrites everything that is an object. For example, if you have an array in an object, you will get separate lines for each element of the array.



So, for the following object:

var x = {
    foo: 17,
    bar: {
        a: 2,
        b: 7
    },
    foobar: [1,2,3]    
}

      

The output will appear:

foo : 17 
a : 2 
b : 7 
0 : 1 
1 : 2 
2 : 3 

      

Obviously there are ways to handle this, but you will need to adapt this feature to suit your requirements.

+6


source


Update . This is how you can do it (taken from one of the links below):

for (var key in validation_messages) {
   var obj = validation_messages[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

      

This is a possible duplicate:



Iterating through object properties

How do I execute a simple JavaScript object with objects as members?

you can find your answer in the above posts.

0


source







All Articles