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?

3
  • Which variable have you equated your json object to? Can you put in ur entire code in a jsbin and show? Commented May 13, 2015 at 7:59
  • 2
    you need resultset[i]['day'+j]; this called bracket notation Commented May 13, 2015 at 8:01
  • possible duplicate of Dynamically access object property using variable Commented May 13, 2015 at 8:09

4 Answers 4

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];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.