VΛVΛV
VΛVΛV

Reputation: 93

Iterate object inside object

I'm working with Json Object:

var someobj = {
 'key':'value',
 'key':'value',
 'objectkey':{'key':'value','key':'value'}
}

While iterating, i want the result in console.log as:

KEY: key && VALUE: value
KEY: key && VALUE: value
OKEY: key && OKEYVALUE: value

While iterating I only get the first level, I can't seem to get it into the values that are the objects. I guess some sort of length could work:

EDIT2: Now with this inner loop it iterates and I get letters for external values, the inner values get logged completely.

var registration_form = {
    'registration_form':{
        'Display Name':'input',
        'Username':{'inpute':'text','id':'some_id'},
        'Password':'input',
        'Email':'input',
        'Captcha':'input'
    }

};
function iterateNodes(data) {
    for (var key in data){
        var obj = data[key];

        for(var prop in obj){
            if(obj.hasOwnProperty(prop)){
                var inobj = obj[prop];
                for(var prop in inobj){
                    console.log(inobj[prop])
                }
            }else{
                console.log(obj)
            }

        }
    }
}
iterateNodes(registration_form);

Upvotes: 2

Views: 7171

Answers (2)

Luca Rasconi
Luca Rasconi

Reputation: 1105

In general you can iterate over properties of an object in this way:

for (var k in o) {
    if (o.hasOwnProperty(k)) {
        console.log('k: ' + k + ', v: ' + o[k])
    }
}

so you can use recursion to go deeper than one level

function hasproperty(o) {
    if (typeof o === 'object') {
        for (var k in o) {
            if (o.hasOwnProperty(k)) {
                return true;
            }
        }    
    }

    return false;
};

function iterate(o) {
    for (var k in o) {
        if (o.hasOwnProperty(k)) {
            if (hasproperty(o[k])) {
                console.log('within ' + k);
                iterate(o[k]);
                console.log('exit ' + k);
            } else {
                console.log('K: ' + k +  ', V:' + o[k]);
            }
        }
    }
};

Upvotes: 2

Nayana_Das
Nayana_Das

Reputation: 1817

Please try this out:

<script
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>

  var someobj = {
      'key1':'value1',
      'key2':'value2',
      'objectkey3':{'key01':'value01','key02':'value02'}
     };

  jQuery.each(someobj, function(i, val) {

        if (typeof val == 'string'){
            console.log("key : "+i+" value: "+val);
        }else{

            jQuery.each(val, function(j, val2) {
                console.log("key : "+j+" value: "+val2);
            });
        }
      });
</script>

Upvotes: 0

Related Questions