I am working on a social networking site, where users can send messages to each other. I am sending ajax requests to a php file to fetch the messages received by a user in json format, like this:
{"messages":[ {"mid":"1","name":"Sam","msg":"Hi Anna"}, {"mid":"4","name":"Kelly","msg":"Hi Anna"}, {"mid":"5","name":"Sam","msg":"Hi Anna"}, {"mid":"7","name":"Sam","msg":"Hello Anna"}, {"mid":"8","name":"Kelly","msg":"Anna"} ]}
In the above scenario, the user “Anna” is receiving messages from users “Sam” and “Kelly”.
Now i need to parse this json structure to separate the responses from each user, and show them to Anna.
How can i parse this json array to get 2 javascript arrays, so that i can loop them and show the responses?
Assuming you already have the JSON decoded and into a javascript variable:
This results in a data structure that looks like this:
You can then loop though that whenever you need to with:
Or if you know the userName you are interested in, you can index directly into it:
Edit: Apparently, you edited your question and added a message id (
mid) which was not in the data when I wrote this answer. It is unclear what you want to do with that message id. If need be, the data for each user could be an array of objects instead of an array of strings where each object would contain both the message id and the message.