-6

Json Code

{
 "pizza":
 {
   "pepperoni lovers":
   {
      "topping": "pepperoni",
      "crust": "hand tossed"
   },

   "sausage lovers":
   {
      "topping": "sausage",
      "crust": "hand tossed"
   }
 }

}

How could I loop through this and populate an array with just the names?

Heath
  • 1,021
  • 3
  • 12
  • 19

4 Answers4

3

An array of property names? Use this:

var names = Object.keys(data.pizza);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

The classic way to iterate over an object is to use a for .. in loop.

for (prop in obj) {
    val = obj[prop];
}

One possible side-effect of this technique is that you are not guaranteed to iterate over the properties in any particular order. If you know the property names ahead of time, you could create an array of property names and iterate.

Since your objects are nested, you will need to nest two for .. in loops to iterate thoroughly:

for (prop in obj) {
    nested_obj = obj[prop];

    for (nested_prop in nested_obj) {
        nested_val = nested_obj[nested_prop];
    }
}

To get an array of all of the property names, you can build the array like this:

props = [];

for (prop in obj) {
    props.push(prop);
    nested_obj = obj[prop];

    for (nested_prop in nested_obj) {
        props.push(nested_prop);
        nested_val = nested_obj[nested_prop];
    }
}
Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50
1

You can loop through an objects properties with for...in:

a = [];
for (n in pizza) {
    a.push(n);
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Schleis
  • 41,516
  • 7
  • 68
  • 87
  • 1
    This is [not "loop like an array"](http://stackoverflow.com/q/500504/1048572) (though the code is correct here). – Bergi Apr 29 '13 at 21:09
0

jQuery, assuming a correct object

DEMO

var pizzaNames=[],
    data = { "pizza" : {
      "pepperoni lovers":
    {
       "topping": "pepperoni",
       "crust": "hand tossed"
    },
      "sausage lovers":
      {
       "topping": "sausage",
       "crust": "hand tossed"
      }
   }
}
// $.each is IE8 compatible, Object.keys is not
$.each(data.pizza,function(name,val) {
   pizzaNames.push(name);
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • How would you get the values of only pepperoni lovers (topping, crust) if you didn't want to hard code the name "pepperoni lovers"? – Heath May 01 '13 at 11:42
  • I do not understand the question. Can you give me the full use case here? – mplungjan May 01 '13 at 12:47
  • Never mind. I'm coming from the XML world. I didn't know that you can have an array in Json. Once I found that out everything else fell into place. Thanks for answering quickly though. – Heath May 02 '13 at 04:26