Search code examples
javascriptmysqlmysqljs

Access part of a javascript array (mysqljs)


I am pulling data from a database in javascript using mysqljs

I can get the output:

{ 
  "Success": true,
  "Result": [{ 
    "buttonName": "90p"
  }, {
    "buttonName": "£1.90"
  }, {
    "buttonName": "£4.90"
  }]
}

Using:

document.getElementById("output").innerHTML = JSON.stringify(data);

However, how do I access each part of the array.

I have tried:

data[1].buttonName

Any help would be much appreciated.


Solution

  • You need to loop over that array Result.

    For example: data.Result[index].buttonName

    This example loops that array and appends new elements to the div with id output.

    var data = { 
      "Success": true,
      "Result": [{ 
        "buttonName": "90p"
      }, {
        "buttonName": "£1.90"
      }, {
        "buttonName": "£4.90"
      }]
    }
    
    var output = document.getElementById("output");
    data.Result.forEach(function(o) {
      var p = document.createElement('p');
      p.appendChild(document.createTextNode(o.buttonName));
      output.appendChild(p);
    });
    <div id='output'>
    </div>