2016-01-27 225 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是不是对象的第二层