我有以下 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
)。如何获取任意小队中相应用户名的死亡
?
任何帮助将不胜感激。
最佳答案
使用下划线,您可以使用: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
}
]
您可以按球队和用户名过滤结果。球队名称是可选的,但用户名必须匹配。
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, ' '));
关于javascript - 使用 jQuery 或 Underscore.js 获取嵌套对象中字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26801721/