11

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?

2
  • 3
    you have to parse it, result = JSON.parse(JSON.stringify(result)); Commented Feb 14, 2018 at 8:38
  • also try JSON.Stringify(result[0].id); Commented Feb 14, 2018 at 8:39

2 Answers 2

17

Say you have a result array of RowDataPacket from mysql called results. You can use Object.assign(). For example, if you wanted to convert the first element to a regular object:

var normalObj = Object.assign({}, results[0]);

or if you wanted the entire array converted to normal objects:

var normalResults = results.map((mysqlObj, index) => {
    return Object.assign({}, mysqlObj);
});

or more compact syntax:

results = results.map(v => Object.assign({}, v));
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to stringify the result. Just Process the result as it is.

and use currentCar.Id instead of currentCar.id.

1 Comment

What exactly do you mean by "just Process the result"?

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.