我正在通过JSON协议获取每个消息的数据的网络聊天中。通过ajax(),我收到以下信息:
{"id":"33","senderId":"1","message":"My fellow citizens","timestamp":"2014-10-24 11:45:04","conversationid":"2","status":"0"}
senderId是标识用户名的键,因为如果senderId =“ 1”表示Michael已发送消息。该数组具有以下名称:
nameArray = ["Micheal", "Earvin", "Kareem", "Wilt", "Hakeem"]
我尝试了以下代码,但无法正常工作。
senderId = JSON.parse(element.senderId)
for (var i=0; i<senderId.length; i++) {
if (senderId[i] == 1) {
senderId[i] = nameArray[0];
break;
}
}
您知道如何根据nameArray的值更改senderId信息的方法吗?
提前感谢您的回复!
最佳答案
假设元素是对象{"id":"33","senderId":"1","message":"My fellow citizens","timestamp":"2014-10-24 11:45:04","conversationid":"2","status":"0"}
,并且您想将senderId: 1
替换为Micheal
,则可以
element.senderId = nameArray[element.senderId - 1];
Demo