-1

I am a bit new in JavaScript, trying to do the hardcoded part above in a more scalable way with the function below. The 't' + i functions well but do the same with the .t + i

function showInfo(results) {
  var data = results.data

  document.getElementById('t1').innerHTML = [data[0].t1].join(', ')
  document.getElementById('t2').innerHTML = [data[0].t2].join(', ')
  document.getElementById('t3').innerHTML = [data[0].t3].join(', ')
  document.getElementById('t4').innerHTML = [data[0].t4].join(', ')

}
function showInfo(results) {
  var data = results.data

  for (let i = 1; i < data.length; i++) {
    document.getElementById('t' + i).innerHTML = [data[0].t + i].join(', ')
  }
}

1 Answers1

0

do instead:

function showInfo(results) {
  var data = results.data

  for (let i = 1; i < data.length; i++) {
    document.getElementById('t' + i).innerHTML = [data[0]['t' + i]].join(', ')
  }
}
fatima
  • 34
  • 6
  • Worked perfect an the join is not necessary. – Francisco Lozada May 03 '21 at 14:40
  • A solution which includes no hardcoding of the variables and is much more flexible would look like the following. `for (let i = 0; i < data.length; i++) { Object.keys(data[i]).forEach(function(key) { document.getElementById(key).innerHTML(data[i][key]); }); }` In your code however it looks like you only ever want to target data[0], if that really is the case you do not need the for loop on it since you only want the first element. like: `Object.keys(data[0]).forEach(function(key) { document.getElementById(key).innerHTML(data[0][key]); });` – Need_Info May 03 '21 at 14:54