Clément Andraud
Clément Andraud

Reputation: 9269

Retrieve a json element without knowing the name

I have a JSON object like this :

var saveChamp = {
      "champ1": {"type": "radio", "size": 4, "null": null},
      "champ2": {"type": 3, "size": 4, "null": null}
    };

alert(saveChamp.champ1.type);

In this example, alert display "radio", it's normal.

How can i do if i don't know champ1 or champ2 for retrieve "type" or "size" ? I create my json dynamically so i can't know all name of my objects.

Thanks you !

Upvotes: 1

Views: 192

Answers (1)

Sirko
Sirko

Reputation: 74036

You can use the for ... in syntax, to retrieve all elements of an objects, whose name you don't know in before (see MDN).

Note the hasOwnProperty() clause (MDN). This prevents JavaScript from going up in the prototype chain and only work on properties of the object itself. So you wont get the default methods of Object for example.

var saveChamp = {
      "champ1": {"type": "radio", "size": 4, "null": null},
      "champ2": {"type": 3, "size": 4, "null": null}
    };

var el;
for( el in saveChamp ) {
  if( saveChamp.hasOwnProperty( el ) ) {
    alert( saveChamp[el].type );
  }
}

Upvotes: 3

Related Questions