0

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!

2 Answers 2

1

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];

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

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");

1 Comment

I don't need the record of the sender in my case, so I will use Sadikhasan's and Arun's solution. But the attribute that you add is also helpful and I am going to add it too. In any case, thanks for your help eusoj :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.