0

I have a JSON object similar to this

{
  emp_name:'',
  day1:'',
  day2:'',
  day3:'',
  .....
  dayn:''
}

I want to get this value dynamically using javascript and display it in a table. Below is what I am trying to do.

for(var i = 0; i < 2; i++)
{
  var row1  = body.insertRow(i);
  var name  = resultset[i].emp_name;
  var cell1 = row1.insertCell(0);

  cell1.innerHTML=name;
  cell1.setAttribute('id', 'emp_name');

  for(var j = 1; j < 32; j++)
  {
    var cell2=row1.insertCell(j);
    cell2.innerHTML = resultset[i].day + j;
  }
}

But the second cell value is not getting populated. I am getting NaN. The problem is because of day + j. Can someone say how to approach this?

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
Gopi Nath
  • 413
  • 3
  • 7
  • 21
  • Which variable have you equated your json object to? Can you put in ur entire code in a jsbin and show? – wallop May 13 '15 at 07:59
  • 2
    you need `resultset[i]['day'+j];` this called [bracket notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Bracket_notation) – Grundy May 13 '15 at 08:01
  • possible duplicate of [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Grundy May 13 '15 at 08:09

4 Answers4

3

As I understood, you want to access the property, which is day{n}, right?

If so, you have to change

resultset[i].day+j;

To

resultset[i]['day'+j];
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
0

The code you have is identical to (resultset[i].day) + j - that means take the value of (nonexistant) day property from resultset[i], and add j to id. That's why you get a NaN.

Whould you should be doing is:

 for(var j=1;j<32;j++){
      var cell2=row1.insertCell(j);
        cell2.innerHTML=resultset[i]['day'+j];
 }
Amit
  • 45,440
  • 9
  • 78
  • 110
0

If one day, the number of properties or items change, you can loop in your dynamic object without changing your code :

for (i = 0, l=resultSet.length; i < l; i++) {
    var row1 = body.insertRow(i);
    var result = resultSet[i];
    var name = result.emp_name;

    var keys = Object.keys(result);
    for (var j = 1, m=keys.length; j < m; j++) {
        var cell2 = row1.insertCell(j);
        cell2.innerHTML = result[keys[j]];
    }
}
jmgross
  • 2,306
  • 1
  • 20
  • 24
0

Since you have tagged jquery too, I have given the answer using jquery. You can accomplish it using $.each function of jquery.

$.each(jsonString,function(key,value){
//You can perform your operations here
console.log(key+'=>'+value); 

});

Visit here for more info jQuery.each

Abhinav
  • 8,028
  • 12
  • 48
  • 89