1

i have this json :

{"name0":"value","name1":"value","name2":"value","name3":"value","name4":"value"}

as you can see "name" incremente in each value, how can I acces to each value in jquery,

i know , that I can acces to a single value with : json.name1 for example but name is a incrementable variable . i need all values to put all on a html list, but this value maybe be 1 or 100

need I a special java script library, or something??

how can i access to each value??

Andy
  • 29,707
  • 9
  • 41
  • 58
Pablo Ortuño
  • 169
  • 2
  • 9

2 Answers2

2

You can get all the values by looping through the Javascript Object:

var yourObject = {"name0":"value","name1":"value","name2":"value","name3":"value","name4":"value"}

for(var key in yourObject) {
  // important check that this is objects own property 
  // not from prototype prop inherited
  if(key.hasOwnProperty(key)){
    var value = yourObject[key]
    // Put value in a html list here
  }
}

source: How to Loop through plain JavaScript object with objects as members?

I hope this helps solving your problem.

Community
  • 1
  • 1
Joren
  • 3,068
  • 25
  • 44
0

Order seems important here, so if you don't care about older browsers, you can just do:

var key, value;

for (var i = 0; i < Object.keys(your_object).length; i++) {
    key = "name" + i;
    value = your_object[key];
}

If you do care about older browsers (FF3.6, IE8), use the uglier version:

var key, value;
var num_properties = 0;

for (var key in your_object) {
    if (your_object.hasOwnProperty(key)) {
        num_properties++;
    }
}

for (var i = 0; i < num_properties; i++) {
    key = "name" + i;
    value = your_object[key];
}

Also, if order isn't important, a for...in loop will work.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496