Reputation: 639
I'm quite new javascript and am having trouble extracting data from an ajax request before loading to a webpage.
The data from the ajax request is something like:
{
"success": {
"user1": [
["2018-01-30", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-29", {
"Type": "None",
"Body": "Message 1"
}]
],
"user2": [
["2018-01-28", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-27", {
"Type": "None",
"Body": "Message 1"
}]
],
"user3": [
["2018-01-26", {
"Type": "None",
"Body": "Message 2"
}],
["2018-01-25", {
"Type": "None",
"Body": "Message 1"
}]
]
}
I can extract the Type
and Body
data using the below code, Which lists all the items out on the webpage.
$.ajax(
{
url : '/ajax_get_messages',
type: "GET",
dataType : 'json'
}).done(function(messages)
{
$.each(messages.success, function(index, message)
{
$('#messages').append(`
<div class='message'>New Sender`)
$.each(message, function(index, item)
{
$('#messages').append(`
<p>Date: ${item[0]} | Type: ${item[1]['Type']} | Body: ${item[1]['Body']}</p>
</div>`)
});
});
})
What I'm struggling to do is get the user's names user1
, user2
etc and put it in place of `New Sender', so all the messages from a user are grouped together in it's own div. I've looked at Object.keys but that didn't seem to be correct for this.
I'm also aware that the appending to the html isn't working correctly because of the $.each(message, function(index, item)
in the middle. Is there a way around this?
Upvotes: 0
Views: 42
Reputation: 13840
The JSON you provided is invalid, but I cleaned it up. You should be able to use the index
in the first loop to get the name:
You can always console.log
the current element in any loop to see exactly what's available to you
Upvotes: 1