Timothée HENRY
Timothée HENRY

Reputation: 14614

Javascript for loop through JSON values

I have a json object r:

[ 
  {
    "id"     : "3443",
    "name"   : "Joe",
    "date1"  : "254",
    "date4"  : "261"
  },
  { "id"     : "50942",
    "name"   : "John",
    "date2"  : "192",
    "date4"  : "195"
  },
  { "id"     : "2524",
    "name"   : "Mary",
    "date1"  : "153",
    "date4"  : "163"
  }
]

and I wish to have a Javascript For loop to go through the dateX values. I know that X is between 1 and a Max value.

But following code does not work:

for (j=1; j<=Max; j=j+1) {
  datestring = 'date' + j;
  if (isset(r[i].datestring)) value[j] = r[i].datestring;
  else value[j] = null; 
}

Forgot to explain that I defined the isset function as:

function isset(variable) {
  return typeof(variable) != "undefined" && variable !== null;
} 

Upvotes: 0

Views: 4117

Answers (3)

castis
castis

Reputation: 8223

disclaimer: if you came here looking for an example of looping through JSON values in the same method that the original poster is asking, Ates answer below mine is a much much better method, please do not use this one.

Im not sure why you'd want to do whatever you're trying because you're going to be overwriting values in value like crazy but you probably know more about what you're doing than we do so heres a working example based on your code.

var r = [
{
"id":"3443",
"name":"Joe",
"date1":"254",
"date4":"261"
},
{
"id":"50942",
"name":"John",
"date2":"192",
"date4":"195"
},
{
"id":"2524",
"name":"Mary",
"date1":"153",
"date4":"163"
}
];


var max = 10; // guess

var value = {};

for(var i in r)
{
    for (j=0; j<=max; j++)
    {
        datestring = 'date'+j;

        if (undefined != r[i][datestring])
        {
            value[j] = r[i][datestring];
        }
        else
        {
            value[j] = null;
        }
    }
}

Upvotes: 1

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140152

First iterate through the array of objects with an ordinary for loop. Then iterate through the properties of each object with for (var p in obj) and check the value of p. Something like:

for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];

    for (var p in obj) {
        if (/^date\d+$/.test(p)) {
            var value = obj[p];
            // p is a dateX property name and value is the value
        }
    }
}

It's counter-intuitive and inefficient to loop through all possible property values to check their existence. Instead, loop through the actual properties and test their names against your pattern.

Upvotes: 10

Jeremy
Jeremy

Reputation: 22435

You are looking for a property called datestring when you should be doing r[i][datestring] or r[i]['date'+j]. This will read the value of the variable and look a property with that name.

Upvotes: 3

Related Questions