在Javascript中访问嵌套对象内的数组值

时间:2018-02-11 07:15:18

标签: javascript arrays json

我相信我们日常生活中使用的JSON对象类型很少:

具有键值属性的对象:

schema

包含值作为数组的对象:

{
    "key" : "value",
    "key" : "value",    
    "key" : "value"
}

包含作为对象数组的值的对象:

{                      
    "key" : "value",
    "key" : "value",        
    "key" : ["value1", "value2", "value3"], 
}

包含具有键值属性的嵌套对象的对象,其中value是对象数组:

{                 
    "key" : "value",
    "key" : "value",        
    "key" : [
        {"key" : "value"},
        {"key" : "value"},
        {"key" : "value"},
    ]
}

我已经访问了key1对象,并且在key1对象中有一个包含所有键的数组。也就是说,

{                    
    "key" : "value",
    "key" : "value",        
    "key1" : {
        "key11" : [  
            {"key" : "value"},  
            {"key" : "value"}       
        ],
        "key12" : [  
            {"key" : "value"},  
            {"key" : "value"}       
        ],
        "key13" : [  
            {"key" : "value"},  
            {"key" : "value"}           
        ]
    }
}

我想遍历key1中的所有键值属性,并循环遍历" key11"," key12",...

如何实现?

1 个答案:

答案 0 :(得分:1)

!(function(){
  //data always like this:
  // this just an array 
  var json_array = [
    {id:1, name:"alex", age: 11},
    {id:2, name:"bob", age: 12},
    {id:3, name:"nn", age: 13},
  ];
 
  // page total_page don't need loop, direct use it
  var json_object = {
    page: 1,
    total_page: 20,
    total_item: 300,
    list: [
      {id:1, name:"alex", age: 11},
      {id:2, name:"bob", age: 12},
      {id:3, name:"nn", age: 13},
    ]
  }
  // or   for(var id in list_object){ console.log(list_object[id]['name'])  }
  var list_object = {
    1: {id:1, name:"alex", age: 11},
    2: {id:2, name:"bob", age: 12},
    3: {id:3, name:"nn", age: 13},
  }
  
  // your data need some change
  var data = {                    
      "key" : "value",
      "key" : "value",        
      "key1" : {

          "key11" : [
              {"key" : "value"},
              {"key" : "value"}
          ],

          "key12" : [
              {"key" : "value"},
              {"key" : "value"}
          ],
          "key13" : [
              {"key" : "value"},
              {"key" : "value"}
          ],
      }
  }
  
  // loop object
  for(var i in data['key1']){
    // loop array
    data['key1'][i].map(function(item, i){
      console.log(item['key'])
    })
  }

})()