0

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?

8
  • Do you have an Id field within each result object in results? Commented May 27, 2017 at 15:27
  • @Pete: Yes, Id is in every result Commented May 27, 2017 at 15:29
  • 1
    Can you share the result of console.log("resultset"+results);? Commented May 27, 2017 at 15:31
  • ok there we go. My resultset log = resultset:[object Object],[object Object]! Commented May 28, 2017 at 8:59
  • [object Object] is the result! Get nothing else. Commented Jun 1, 2017 at 15:31

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

I still get -> ID: undefined
Isn't the results is of the form [[{"Id":"xx123","date":2017-05-24 19:59:21 }],[{"Id":"xx456","date":2017-05-24 19:59:21 }]] ?
the (stringify) result is : [{"Id":"xxx123","date":2017-05-24 19:59:21}] [{"Id":"xxx124","date":2017-05-24 20:00:01}] [{"Id":"xxx125","date":2017-05-24 20:00:03}]
Okay! That's different from one provided earlier. We don't have an outer [] there. right?
|

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.