2011-04-20 69 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看到。