使用jQuery或Underscore.js获取嵌套对象中的字段值

时间:2014-11-07 12:55:05

标签: javascript jquery underscore.js

我有以下JS对象:

{
   "gameName":"Shooter",
   "details":[
      {
         "submitted":1415215991387,
         "author":"XYZ",
         "subPlayer":{
            "members":{
               "squad1":[
                  {
                     "username":"John",
                     "deaths":0
                  }
               ]
            },
            "gameSlug":"0-shooter"
         }
      }
   ],
   "userId":"foL9NpoZFq9AYmXyj",
   "author":"Peter",
   "submitted":1415215991608,
   "lastModified":1415215991608,
   "participants":[
      "CXRR4sGf5AdvSjdgc",
      "foL9NpoZFq9AYmXyj"
   ],
   "slug":"1-shooterConv",
   "_id":"p2QQ4TBwidjeZX6YS"
}

我想让正确的用户死亡。

我目前的代码是这样的:

$.map(this.details.subPlayer.members.squad1, function(obj) {
            if(obj.username == Meteor.user().username) {
                return obj.deaths;
            }
        });

然而,问题是我不确切知道小队名称(例如squad1)。如何获得任何小组中相应用户名的deaths

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

使用下划线,您可以使用:data.details[0].subPlayer.members

var data = {
   "gameName":"Shooter",
   "details":[
      {
         "submitted":1415215991387,
         "author":"XYZ",
         "subPlayer":{
            "members":{
               "squad1":[
                  {
                     "username":"John",
                     "deaths":0
                  }
               ]
            },
            "gameSlug":"0-shooter"
         }
      }
   ],
   "userId":"foL9NpoZFq9AYmXyj",
   "author":"Peter",
   "submitted":1415215991608,
   "lastModified":1415215991608,
   "participants":[
      "CXRR4sGf5AdvSjdgc",
      "foL9NpoZFq9AYmXyj"
   ],
   "slug":"1-shooterConv",
   "_id":"p2QQ4TBwidjeZX6YS"
}
function getDeaths(data) {
    var members = data.details[0].subPlayer.members;
    return _.map(members, function(key, value){
        return {
            member: value,
            deaths: members[value][0].deaths
        }
    });
}

console.log(JSON.stringify(getDeaths(data), null, '  '));

返回:

[
  {
    "member": "squad1",
    "deaths": 0
  }
]

您可以按小队和用户名过滤结果。 squadname是可选的,但用户名必须匹配。

function getDeaths(data, username, squad) {
    var users = [];
    var members = data.details[0].subPlayer.members;
    _.each(members, function(squads, squadName) {
        if (!squad || (squad && squadName === squad)) {
            _.each(squads, function(user, index) {
                if (user.username === username) {
                    users.push(user);
                }
            })
        }
    });
    return users;
}
var deaths = getDeaths(data, 'John', 'squad1');
console.log(JSON.stringify(deaths, null, '  '));