Jquery数组迭代json

时间:2014-03-26 05:52:09

标签: jquery iteration

如何遍历Json对象?

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()
    }
});

当我在JSON对象上调用children函数时,它不会让孩子们接受。

子函数是否仅适用于不在JSON上的DOM元素?

如何遍历JSON对象并获取列值?

3 个答案:

答案 0 :(得分: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);
    });
})

看看这个迭代。 jsfiddle

答案 1 :(得分:0)

这是你需要的吗?请检查

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);
});

答案 2 :(得分:0)

迭代JSON对象

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);