0

How to iterate through the Json object?

var obj = { "field": {"row1" : {"col1":10,"col2":20,"col3":30},"row2" : {"col1":20,"col2":30,"col3":40}}}

$(obj).each(function(i,val) {
    child_obj =val
    while(children = child_obj.children() ) {
        child_obj = children .children()
    }
});

When I call children function on JSON object it does not get the children.

Will children function work only on DOM elements not on JSON?

How to loop through the JSON object and get the column values?

B L Praveen
  • 1,812
  • 4
  • 35
  • 60

3 Answers3

0
var obj = { "field": {"row1" : {"col1":10,"col2":20,"col3":30},"row2" : {"col1":20,"col2":30,"col3":40}}}
$.each(obj.field,function(i,val){
    console.log(val);
    $.each(val, function(col, colVal){
        console.log(col);
        console.log(colVal);
    });
})

Have a look on this iteration. jsfiddle

Amit Garg
  • 3,867
  • 1
  • 27
  • 37
  • It is working with the sample data I have pasted here. But doesnot work on my system. When I do foreach it returns the whole object with key. JSON DATA Object { "field": Object { row1: {"col1":10,"col2":20,"col3":30}} } – B L Praveen Mar 26 '14 at 06:33
0

Is this the one you needed? Please check

var obj = { "field": {"row1" : {"col1":10,"col2":20,"col3":30},"row2" : {"col1":20,"col2":30,"col3":40}}}
$.each(eval(obj.field), function(i, val){
    console.log(val.col1+','+val.col2+','+val.col3);
});
Rohit Subedi
  • 560
  • 3
  • 13
0

To Itereate through the JSON objects

Demo

var root = {
    leftChild: {
        leftChild: {
            leftChild: null,
            rightChild: null,
            data: 42
        },
        rightChild: {
            leftChild: null,
            rightChild: null,
            data: 5
        }
    },
    rightChild: {
        leftChild: {
            leftChild: null,
            rightChild: null,
            data: 6
        },
        rightChild: {
            leftChild: null,
            rightChild: null,
            data: 7
        }
    }
};
function getLeaf(node) {
    while(node instanceof Object) {
    if (node.leftChild) {
        node = getLeaf(node.leftChild);
    } else if (node.rightChild) {
        node = getLeaf(node.rightChild);
    } else { // node must be a leaf node
        return node;
    }
        console.log(node);
   }
}

alert(getLeaf(root).data);
B L Praveen
  • 1,812
  • 4
  • 35
  • 60