0

I have problem fetching key values of inner levels of object.

This is the sample object

{  
"dataset":{  
  "Categories":[  
     {  
        "Desserts":[  
           "Sweets",
           "Ice Creams",
           "Pastry",
           "Moose",
           "Jelly",
           "Donut",
           "Custard",
           "Puddings",
           "Cookies",
           "Pies"
        ]
     },
     {  
        "Juices and Beverages":[  
           "Cold",
           "Hot",
           "Fresh",
           "Mocktail",
           "Sodas"
        ]
     },
     {  
        "Indian Breads":[  
           "Plain",
           "Stuffed"
        ]
     },
     {  
        "Salads":[  
           "Green",
           "Vegetable",
           "Fruit"
        ]
     },
     {  
        "Soups":[  
           "Clear",
           "Thick"
        ]
     }
  ]
  }
 }

I tried interating through the object on the outer level.

for(var k in dataset.Categories)
    categories.push(k);

But I get the result as 0,1,2,3,4.

How do I get the key values a level inside? Like "Desserts","Juices and Beverages",....

Aravind Bharathy
  • 1,540
  • 3
  • 15
  • 32

2 Answers2

1

Categories is an array, so if you use for..in on it, the values you will get are array indices.

To get the values you want, you can use:

var categoryNames = dataset.Categories.map(function (item) {
    return Object.keys(item)[0];
});

example

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

You are inserting indexes instead of value. Code is untested but should work.

for(var k in dataset.Categories)
categories.push(dataset.Categories[k]);
qamar
  • 1,437
  • 1
  • 9
  • 12