2

Since there seems nobody is able to find a solution for my problem, I would like to ask my question in a different way: What should be the correct way to loop through the games section of the following object:

[
    {
        "_id": "5710b0ddab8b724011705037",
        "username": "test",
        "name": "testuser",
        "__v": 0,
        "library": {
            "games": [
                {
                    "platform": [
                        "17",
                        "94"
                    ],
                    "name": "Simcity",
                    "id": "37620"
                },
                {
                    "platform": [
                        "146",
                        "20"
                    ],
                    "name": "destiny",
                    "id": "36067"
                }
            ],
            "platforms": [
                {
                    "name": "Xbox360",
                    "id": "20"
                },
                {
                    "name": "PC",
                    "id": "94"
                }
            ]
        }
    }
]

This object is fetched out through mongoose out of a MongoDB, all happens in the API section of my NodeJS application:

.get('/test', function(req, res){
    User.findOne({"username": req.decoded.username}, function(err, user){

        // trying to loop here

    });
})

I have tried everything I find, but I cannot get it to work, so I wonder what ways you use to do this, without cluttering your vision with my (maybe wrong) ways and errors...

Community
  • 1
  • 1
stijnpiron
  • 359
  • 2
  • 4
  • 15
  • JSON is a *textual notation* for data exchange. If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. If you **are** dealing with a string, the first step is to parse it: `var o = JSON.parse(stringContainingJSON);` – T.J. Crowder Apr 17 '16 at 09:39
  • Your edit *markedly* changes the structure of the data. Please ensure that your question is correct *before* posting it, to avoid wasting everyone's time. – T.J. Crowder Apr 17 '16 at 09:54
  • Yes, I was unaware I had copied the wrong part, my apologies – stijnpiron Apr 17 '16 at 09:57
  • The only reason this wasn't a duplicate of your earlier question was the difference in the quoted structure. With that gone, it's an exact duplicate. You can edit that question to add details, etc. Fundamentally, you need to debug this using a debugger. – T.J. Crowder Apr 17 '16 at 10:08

2 Answers2

2

Updated Answer:

Your edit markedly changes the structure of the data compared to your original question.

Now, you have an array containing one entry, which has library, which has games, so you reference it (assuming user points to the whole thing) as user[0].library.games. E.g.:

user[0].library.games.forEach(function(entry) {
    // Use `entry` here
});

var user = [{
  "_id": "5710b0ddab8b724011705037",
  "username": "test",
  "name": "testuser",
  "__v": 0,
  "library": {
    "games": [{
      "platform": [
        "17",
        "94"
      ],
      "name": "Simcity",
      "id": "37620"
    }, {
      "platform": [
        "146",
        "20"
      ],
      "name": "destiny",
      "id": "36067"
    }],
    "platforms": [{
      "name": "Xbox360",
      "id": "20"
    }, {
      "name": "PC",
      "id": "94"
    }]
  }
}];

user[0].library.games.forEach(function(entry) {
  log(entry.name);
});

function log(msg) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

Original Answer:

games is an array, assuming you have o referencing that object, you can reference it from o.user.library.games.

There are lots of ways to loop over arrays (see this answer for a list); one of them is forEach:

o.user.library.games.forEach(function(entry) {
    // Use `entry` here, e.g. `entry.name`, `entry.id`, etc.
});

E.g.:

var o = {
  "user": {
    "name": "testuser",
    "library": {
      "platforms": [{
        "id": "20",
        "name": "Xbox360"
      }, {
        "id": "94",
        "name": "PC"
      }],
      "games": [{
        "id": "37620",
        "name": "Simcity",
        "platform": [
          "17",
          "94"
        ]
      }, {
        "id": "36067",
        "name": "destiny",
        "platform": [
          "146",
          "Xbox360"
        ]
      }]
    }
  }
};
o.user.library.games.forEach(function(entry) {
  log(entry.name);
});

function log(msg) {
  var p = document.createElement('p');
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

From your comment below, it sounds like the structure may not be quite as you quoted it in the question. You can use node-inspector to debug your NodeJS code, set a breakpoint at the beginning of where you want to loop, and inspect the variable you have referring to the object. That will show you its structure. It's very easy to install (npm install -g node-inspector) and use (node-debug your-main-file.js).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This is exactyl what I am trying all the time, but I always get the error `user.library.games.forEach(function(entry) {` `TypeError: user.library.games.forEach is not a function` – stijnpiron Apr 17 '16 at 09:45
  • @stijnpiron: Note the `o.` at the beginning of mine. You have a `user` key on the top-level object; the top-level object isn't, itself, the user. If you've already grabbed that, then what you have isn't as quoted in your question, or you're using a **very** old JavaScript engine that doesn't have `forEach` (introduced in 2009, as part of ES5); although if you're using Node, I don't think there was ever a version that didn't have it. – T.J. Crowder Apr 17 '16 at 09:46
  • I have updated my question, The data is fetched, not hardcoded, so I don't have an "o" variable... – stijnpiron Apr 17 '16 at 09:51
  • @stijnpiron: You have the data referenced from *some* variable. `o` is an *example*. – T.J. Crowder Apr 17 '16 at 09:53
  • When I try it with `user[0]` I get an `TypeError: Cannot read property 'library' of undefined`error... – stijnpiron Apr 17 '16 at 10:01
  • @stijnpiron: Then the structure isn't as you've quoted. See my suggestion at the end of the answer. – T.J. Crowder Apr 17 '16 at 10:07
2

Use for...in to loop through Javascript/JSON objects

for (variable in object) {...
}

for...in documentation

Use forEach to loop through Javascript/JSON arrays

arr.forEach(callback[, thisArg])

forEach documentation

shikhar
  • 2,431
  • 2
  • 19
  • 29