Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139923

Convert NodeJs MySQL result to accessible JSON Object

$
0
0

I want to get some data from my database. Example:

  getCarIds: function (callback) {
    db.query("SELECT Id FROM Cars;",
      function (err, result) {
        if (err) throw err;

        result = JSON.stringify(result);

        var cars = [];

        for (var i = 0; i < result.length; i++) {
          var currentCar = result[i];
          var carId = currentCar.id;
          cars.push(carId);
        }

        callback(cars);
      });
  }

I want to store all the ids into an array. Like

cars = [1,2,3,4,5];

The result returns this

[ RowDataPacket { Id: '1' },
  RowDataPacket { Id: '2' },
  RowDataPacket { Id: '3' } ]

So I try to convert it by writing

result = JSON.stringify(result);

this returns me

[{"Id":"1"},{"Id":"2"},{"Id":"3"}]

when I want to access this object by writing

result[0]

I get

[

so obviously

result[0].id

will return

undefined

How can I get all the ids from the object?


Viewing all articles
Browse latest Browse all 139923

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>