Reputation: 1263
I am working on a webchat that gets data of every message through a JSON protocol. Through ajax() I receive the following information:
{"id":"33","senderId":"1","message":"My fellow citizens","timestamp":"2014-10-24 11:45:04","conversationid":"2","status":"0"}
The senderId is the key to identify user's name, since if senderId="1" it means that Michael sent the message. The array has the following names:
nameArray = ["Micheal", "Earvin", "Kareem", "Wilt", "Hakeem"]
I tried the following code, but it is not working.
senderId = JSON.parse(element.senderId)
for (var i=0; i<senderId.length; i++) {
if (senderId[i] == 1) {
senderId[i] = nameArray[0];
break;
}
}
Do you know how a way to change the senderId information according to the values of nameArray?
Thanks in advance for your replies!
Upvotes: 0
Views: 152
Reputation: 374
With the object that you have, you don't need a for loop to replace the name. Indeed you can use a direct search into the array including and exception if the senderId doesn't exist in your nameArray.
Also, replace directly an value into the object is not a really good practice, I recommend you add another attribute to the object to have the record of the senderId if you need it in the future.
index = element.senderId - 1;
element.name = (index in nameArray ? nameArray[index] : "Anonymous");
Upvotes: 0
Reputation: 388436
Assuming element is the object {"id":"33","senderId":"1","message":"My fellow citizens","timestamp":"2014-10-24 11:45:04","conversationid":"2","status":"0"}
and you want to replace senderId: 1
with Micheal
, you can
element.senderId = nameArray[element.senderId - 1];
Upvotes: 1