Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top