1

Im trying to get an object array from my MySql database, however I keep getting the result of "undefined" and I do not know why my code:

database.query(sql, (err, rows)=>{
    var data = Object.values(JSON.parse(JSON.stringify(rows)))
    console.log(data[0].type)
})

Whenever I console log my "data" variable I get:

[
  {
    data: '[{"type": "c#", "script": "csharp script"}, {"type": "javascript", "script": "javascript script"}, {"type": "html", "script": "html script"}]'
  }
]

which seems correct to me but Im not sure about what to do now. Any help would be greatly appreciated

  • First of all, there's no need to stringify then parse again. This does create a copy, but that's pointless here. In theory you need `rows[0].data[0].type` but it seems like `.data` is a string so you need `JSON.parse(rows[0].data)[0].type` –  May 21 '21 at 10:31

1 Answers1

0

The actual data you need is inside the first element's .data property. It's a string, so you need to parse it to use as an array of objects.

Working example

let yourData = [{
  data: '[{"type": "c#", "script": "csharp script"}, {"type": "javascript", "script": "javascript script"}, {"type": "html", "script": "html script"}]'
}]

let data = JSON.parse(yourData[0].data)
console.log(data[0].type)
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39