Reputation: 597
i have a Json Object and want to loop thorugh it. In my loop I want to execute a select query and save it result to another json Array.
So I start with a loop, performe a mysql query and want just log the results:
for (var x = 0; x < obj.length; x++) {
var query = connection.query('SELECT Id, date FROM tbl1 WHERE Id LIKE '+ mysql.escape(obj[x].ident) +'; SELECT Id, date FROM tbl WHERE Id LIKE '+ mysql.escape(obj[x].ident) +' ORDER BY date DESC Limit 1 offset 1', function (error, results, fields) {
if (error) {throw error;}
if (!error) {
console.log("resultset"+results); //<- Here I get the right result
console.log("ID: "+results[0].Id); //<- UNDEFINED
console.log("ID-LAST-entry: "+ results[1].Id); //<- UNDEFINED
} });
The Problem is that for booth results (0 and 1) i get = UNDEFINED.
Where is my mistake?
Upvotes: 0
Views: 899
Reputation: 1697
From the value of results
, You can see that it is NOT an array of objects
instead it is an array
of arrays where each item is an object
.
You need to iterate inner array to get the Id
. See the snippet below. Parsing the result into JSON and then reads the required data.
if (!error) {
var parsedResults = JSON.parse(JSON.stringify(results));
var outerArraySize = parsedResults.length;
for (var outerIndex = 0; outerIndex < outerArraySize; ++outerIndex) {
var innerArraySize = parsedResults[outerIndex].length;
for (var innerIndex = 0; innerIndex < innerArraySize; ++innerIndex)
console.log("ID: " + parsedResults[outerIndex][innerIndex].Id);
}
}
Upvotes: 1