我有一个字符串,我从api调用中获取,然后使用JSON.parse(meetResponse)将其解析为对象
meetResponse = {
"returncode":"SUCCESS",
"meetingName":"bbb meeting",
"meetingID":"712",
"createTime":"1457969919738",
"createDate":"Mon Mar 14 11:38:39 EDT 2016",
"voiceBridge":"35014",
"dialNumber":"613-555-1234",
"attendeePW":"PDmAJD4n",
"moderatorPW":"mpassword",
"running":"true",
"duration":"0",
"hasUserJoined":"true",
"recording":"true",
"hasBeenForciblyEnded":"false",
"startTime":"1457969919743",
"endTime":"0","participantCount":"2",
"maxUsers":"20",
"moderatorCount":"2",
"attendees":{
"attendee":[
{
"userID":"10005655",
"fullName":"Snedden Gonsalves",
"role":"MODERATOR",
"customdata":{}
},{
"userID":"10005656",
"fullName":"SneddenReg Gonsalves",
"role":"MODERATOR",
"customdata":{}
}
]
},
"metadata":{},
"messageKey":{},
"message":{}
}
我想解析“与会者”下的“与会者”,看看谁在场
我现在使用的逻辑是:
//check if current user is already present in the meeting
for (var key in meetInfo.attendees.attendee){
console.log('key:',meetInfo.attendees.attendee[key]);
console.log(meetInfo.attendees.attendee[key].userID+"==="+user_id);
if(meetInfo.attendees.attendee[key].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
}
else{
inMeeting=false;
}
}
这项工作是有一个以上的与会者,但对于一个与会者,它失败了。 我正在寻找可以为任何数量的'与会者'工作的东西。
我还尝试meetInfo.attendees.length
代替Object.keys(meetInfo.attendees).length
,但它不喜欢它
答案 0 :(得分:1)
听起来你的attendees.attendee
属性可以是多个数组,也可以是奇异对象。如果是数组,key
块中的for..in
变量将填充index
。当它是一个对象时,它将用属性键填充。
两件事。首先,您可以通过将值与空数组连接来确保始终使用数组:
var attendeeList = [].concat(meetInfo.attendees.attendee);
其次,您不应该使用for..in
来迭代数组。请使用经典的for循环:
for (var idx= 0; idx < attendeeList.length; idx++)
console.log('key:',attendeeList[idx]);
console.log(attendeeList[idx].userID+"==="+user_id);
if(attendeeList[idx].userID===user_id){
console.log('in meeting..');
inMeeting=true;
break;
} else{
inMeeting=false;
}
}
Bonus,如果数组中的任何项匹配,则此循环设置变量true
。这有一个特殊的Array函数:
inMeeting = [].concat(meetInfo.attendees.attendee)
.some(function(a){
return a.userID === user_id;
});