[英]Get value of field in nested object with jQuery or 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
?
任何帮助将不胜感激。
使用下划线,您可以使用: 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, ' '));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.