Search code examples
javascriptobject-literal

Dereferencing Javascript objects


I have a simple data structure:

var data = function () {
    return {
        users: [
            {
                _id: 1,
                firstname: 'Bob'
                posts: [
                    {
                        _id: 1,
                        text: 'Great post',
                        posted_to: [2, 3, 4]  // user id's
                    }
                ]
            }
        ]
    }
}

What is the best way to dereference the users in posted_to so that when I access users[0].posts[0].posted_to I get a list of user objects, not just the id's?


Solution

  • var data =  {
        users: [
            {
                _id: 1,
                firstname: 'Bob',
                posts: [
                    {
                        _id: 1,
                        text: 'Great post',
                        posted_to: [2, 3, 4]
                    }
                ]
            },
            {_id:2},{_id:3},{_id:4}
        ]
    }
    
    function getUsersPostedTo() {
      var result = [];
      var postedToIds = data.users[0].posts[0].posted_to;
    
      for (var i = 0; i<postedToIds.length; i++) {
          var id = postedToIds[i];
          for (var j = 0; j<data.users.length; j++) {
              if (data.users[j]._id == id) {
                  result.push(data.users[j]);
              }
          }
      }
    
      return result;
    }
    
    var users = getUsersPostedTo();
    

    PS: I changed the data function to an object var.