2014-03-26 119 views
0

如何遍歷Json對象?Jquery數組迭代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對象並獲取列值?

+1

那麼,是什麼在這裏實際上是這個問題? –

+0

如何遍歷json對象並獲取col值 –

+0

[Access/process(嵌套)對象,數組或JSON]可能的重複(http://stackoverflow.com/questions/11922383/access-process-nested-objects -arrays-or-json) – Sanoob

回答

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

+0

它正在處理我粘貼在這裏的樣本數據。但是在我的系統上不工作。當我做foreach時,它會用鍵返回整個對象。 JSON DATA \t Object {「field」:Object {row1:{「col1」:10,「col2」:20,「col3」:30}}} –

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

要Itereate通過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);