2016-01-27 280 views
0

返回值我想返回所有table_name領域在我的javascript JSON對象:嵌套的javascript JSON對象

{ 
    "Products": { 
     "Antifreeze": { 
      "table_name":"old_world", 
      "tableFields": 
      [ 
       ["product_code", "Product Code"], 
       ["brand", "Brand"], 
       ["category", "Category"], 
       ["subcategory", "Subcategory"], 
       ["description", "Description"], 
       ["service_interval", "Service Interval"], 
       ["concentration", "Concentration"], 
       ["size", "Size"], 
       ["price", "Price"] 
      ] 
     }, 

     "Lubricants and Greases": { 
      "table_name":"lubricants_grease", 
      "tableFields": 
      [ 
       ["product_code", "Product Code"], 
       ["brand", "Brand"], 
       ["category", "Category"], 
       ["description", "Description"], 
       ["price", "Price"] 
      ] 
     } 
    } 
} 

到目前爲止,我嘗試:

for(var key in Products) { 

    console.log(Products.table_name); 
}; 

但這返回undefined ..有人可以幫忙嗎?

在此先感謝!

+1

嘗試只記錄'key'和值'產品。產品[關鍵]' – charlietfl

+0

完美,謝謝! –

+0

嘗試products.antifreeze [key] –

回答

0

var products = { 
 
    "Products": { 
 
     "Antifreeze": { 
 
      "table_name":"old_world", 
 
      "tableFields": 
 
      [ 
 
       ["product_code", "Product Code"], 
 
       ["brand", "Brand"], 
 
       ["category", "Category"], 
 
       ["subcategory", "Subcategory"], 
 
       ["description", "Description"], 
 
       ["service_interval", "Service Interval"], 
 
       ["concentration", "Concentration"], 
 
       ["size", "Size"], 
 
       ["price", "Price"] 
 
      ] 
 
     }, 
 

 
     "Lubricants and Greases": { 
 
      "table_name":"lubricants_grease", 
 
      "tableFields": 
 
      [ 
 
       ["product_code", "Product Code"], 
 
       ["brand", "Brand"], 
 
       ["category", "Category"], 
 
       ["description", "Description"], 
 
       ["price", "Price"] 
 
      ] 
 
     } 
 
    } 
 
} 
 
var str = ''; 
 

 
for(var key in products.Products) { 
 

 
    for(var key2 in products.Products[key]) 
 
    { 
 
      if(key2 == 'table_name') 
 
      { 
 
       str += products.Products[key][key2]+"\n"; 
 
      } 
 
    } 
 
    
 
}; 
 
console.log(str);

你需要的嵌套循環,因爲table_name是不是對象的第二層