嵌套javascript JSON对象中的返回值

时间:2016-01-27 03:52:52

标签: javascript json object

我正在尝试返回javascript JSON对象中的所有table_name字段:

{
    "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 个答案:

答案 0 :(得分: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不在对象的第二层