简体   繁体   中英

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;
} 

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.

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.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM