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?
-
This looks similar to Get key and value of object in JavaScript?.Heretic Monkey– Heretic Monkey2018年03月30日 16:49:49 +00:00Commented Mar 30, 2018 at 16:49
-
The json you have pasted is throwing syntax error. You should replace it with the correct json response.Anurag Singh Bisht– Anurag Singh Bisht2018年03月30日 17:04:00 +00:00Commented Mar 30, 2018 at 17:04
1 Answer 1
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
2 Comments
.message as an HTML object and then add it when it's done: codepen.io/xhynk/pen/Kooejw?editors=1011