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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With