0

I am trying to return all the table_name fields in my javascript JSON object:

{
    "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"]
            ]
        }
    }
}

So far I tried:

for(var key in Products) {

    console.log(Products.table_name);
};

But this returns undefined... can someone help?

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200

1 Answers1

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);

you need nested loop for this because table_name is not in the second layer of object

歐津柏
  • 94
  • 5