2011-04-20 62 views
1

我有這個對象,我想獲得門戶名稱。 我將如何做到這一點,利用JS或jquery的解析通過對象

OBJECT

var Test = {}; 

Test.Customers = [{"CustomerItems": 
          "Portals": 
          {"id":"1","customer":"1950","resident":"yes", 
          "CustomPortals": 
             [ 
             {"id":"11","test":"4251","portalname":"tye.jpg"}, 
             {"id":"12","test":"4251","portalname":"Lsdf.jpg"}, 
             {"id":"13","test":"4251","portalname":"nick.jpg"} 
             ] 
          } 
        }, 
        {"CustomerItems": 
          "Portals": 
          {"id":"2","customer":"1952","resident":"yes", 
          "CustomPortals": 
             [ 
             {"id":"14","test":"4252","portalname":"Chrysanthemum2.jpg"}, 
             {"id":"15","test":"4255","portalname":"navagin.jpg"}, 
             {"id":"16","test":"4257","portalname":"jasoria.jpg"} 
             ] 
          } 
        }, 
        {"CustomerItems": 
          "Portals": 
          {"id":"3","customer":"1950","resident":"yes", 
          "CustomPortals": 
             [ 
             {"id":"17","test":"4231","portalname":"Zsryanmum1.jpg"}, 
             {"id":"18","test":"4651","portalname":"Ltd1.jpg"}, 
             {"id":"19","test":"4281","portalname":"ser1.jpg"} 
             ] 
          } 
        } 
       ] 

受審

$.each(Test.Customers, function(index, value) { 

       $.each(value.CustomPortals, function(innerIndex, innerValue) { 
        alert('File ' + innerValue + ' in customer ' + innerIndex); 
       }); 

      }); 

但它不工作

感謝

回答

3

你的內心「每()」循環需要穿越‘CustomerItems.Portals’去‘CustomPortals’:

  $.each(value.CustomerItems.Portals.CustomPortals, function(innerIndex, innerValue) { 
       alert('File ' + innerValue + ' in customer ' + innerIndex); 
      }); 

它可能會是添加一些存在測試是個好主意,但你知道你的數據比我更好。

編輯 — @justkt有一個非常好的觀點 - 那就是JSON,正如此處所發佈的,首先無效。因此,我上面寫的是真實的如果的東西可能:-)

2

解析嘗試

alert('File ' + innerValue.portalname + ' in customer ' + innervalue.id); 

代替

alert('File ' + innerValue + ' in customer ' + innerIndex); 
2

當我通過JSONLint跑到你的對象(而我知道JSON比JS對象更嚴格,它是一個簡單的驗證器),它抱怨這個語法:

"CustomerItems" : "Portals" : {} 

通過刪除「門戶」,而是設置:

"CustomerItems" : {} 

,並使用下面的JS:

$.each(Test.Customers, function(index, value) { 

    $.each(value.CustomerItems.CustomPortals, function(innerIndex, innerValue) { 
     alert('File ' + innerValue.portalname + ' in customer ' + innerValue.id); 
    }); 

}); 

我能得到一個工作的迭代器,你可以在行動here看到。