1

Hi I have the following line of code that receives data from an API call and shows them in an HTML page.

$.getJSON("https://localhost:44326/api/Facebook/GetFeed?accessToken=" + response.authResponse.accessToken)
    .done(function (data) {
        $.each(data, function (key, item) {
            console.log(item);
                for (i in item) {
                    $('<li>', { text: 'Message: ' + item[i].message +' Time: '+ item[i].created_time.data }).appendTo($('#wellForFeed'));
                }
        });
    });

Now I wanna know a couple of things. First of all, I am storing both message and time in 1 element and are shown like this:

Message: Test post for my api Time: 2020-06-07T08:53:08+0000

However, I would like to store a message in an element and the time in a separate element. I tried it, however, the result was the messages all together, then the message date and time all together beneath them, as follows:

Message: ABC
Message: DEF
Message: GHI

Time: 2020-06-07T08:53:08+0000
Time: 2020-06-07T08:53:08+0000
Time: 2020-06-07T08:53:08+0000

However, I want them like this:

Message: ABC
Time: 2020-06-07T08:53:08+0000

Message: DEF
Time: 2020-06-07T08:53:08+0000

Message: GHI
Time: 2020-06-07T08:53:08+0000

Additionally, I would like to format my date, but I have no clue how.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Rick Astley
  • 125
  • 1
  • 11

2 Answers2

1

To achieve this you can split the message and created_time in to separate elements which appear on their own line within the parent li. In the example below I used p elements, but this can be amended to suit your needs:

$.getJSON("https://localhost:44326/api/Facebook/GetFeed?accessToken=" + response.authResponse.accessToken).done(function(data) {
  $.each(data, function(key, item) {
    for (i in item) {
      $(`<li><p>Message: ${item[i].message}</p><p>Time: ${item[i].created_time.data}</p>`).appendTo('#wellForFeed');
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Something like this?

Note for the date formatting have a look here

How to format a JavaScript date

const items = [
  { message : "ABC" , created_time: { data : "2020-06-07T08:53:08+0000" }},
  { message : "DEF" , created_time: { data : "2020-06-07T08:53:08+0000" }},
  { message : "GHI" , created_time: { data : "2020-06-07T08:53:08+0000" }}
]

let html = [];
$.each(items, function(i,item) {
  const date = new Date(item.created_time.data);
  html.push('<li>Message: ' +item.message+'</li>')
  html.push('<li>Time: ' + date.toLocaleDateString() + " " + date.toLocaleTimeString() +'</li>')
});
$('#wellForFeed').html(html.join(""))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="wellForFeed">
</ul>
mplungjan
  • 169,008
  • 28
  • 173
  • 236