Reputation: 7094
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?
Upvotes: 0
Views: 719
Reputation: 707776
Assuming you already have the JSON decoded and into a javascript variable:
var response = {
"messages":[
{"name":"Sam","msg":"Hi Anna"},
{"name":"Kelly","msg":"Hi Anna"},
{"name":"Sam","msg":"Hi Anna"},
{"name":"Sam","msg":"Hello Anna"},
{"name":"Kelly","msg":"Anna"}
]
};
var dataByUser = {}, userName;
var msgs = response.messages;
for (var i = 0; i < msgs.length; i++) {
userName = msgs[i].name;
// if we don't have any msgs for this user, then initialize their data structure
if (!dataByUser[userName]) {
dataByUser[userName] = [];
}
dataByUser[userName].push(msgs[i].msg);
}
This results in a data structure that looks like this:
var dataByUser = {
"Sam" : ["Hi Anna", "Hi Anna", "Hello Anna"],
"Kelly": ["Hi Anna", "Anna"]
};
You can then loop though that whenever you need to with:
for (var userName in dataByUser) {
// dataByUser[userName] is the array of messages from userName
}
Or if you know the userName you are interested in, you can index directly into it:
dataByUser["Sam"] // contains array of messages from Sam
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.
Upvotes: 3
Reputation: 629
Take your upcoming encoded json into the variable like
var messages = jQuery.parseJSON('StringSourceOfYourJsonEncoded');
jQuery(messages).each(function(index,value) {
// GET THE OBJECT DATA FROM HERE.
alert(messages.msg);
});
Hope, this will works.
Upvotes: 1