skip to Main Content

I have a JSON Array of messages that I need to convert into html elements to use for displaying in my web page. The JSON that I’m receiving looks like this:

    {
    "data": [
        {
            "fieldData": {
                "Message": "Message 1",
                "Timestamp": "04/14/2023 11:39:13"
            }
        },
        {
            "fieldData": {
                "Message": "Message 2",
                "Timestamp": "04/13/2023 10:02:18"
            }
        },
        {
            "fieldData": {
                "Message": "Message 3",
                "Timestamp": "08/19/2021 19:51:21"
            }
        }
    ]
}

I need to extract each ‘Message’ and ‘Timestamp’ Value from the Array and place them in tags like the following for the first array:

<p class="from-them">Message 1</p>
<time class="timestamp-to">04/14/2023 11:39:13</time>

So using the sample JSON above the end result would be:

<p class="from-them">Message 1</p>
<time class="timestamp-to">04/14/2023 11:39:13</time>
<p class="from-them">Message 2</p>
<time class="timestamp-to">04/13/2023 10:02:18</time>
<p class="from-them">Message 3</p>
<time class="timestamp-to">08/19/2021 19:51:21</time>

It’s my first time trying to write a JavaScript function to convert an array into individual html elements and not sure where to start here.

2

Answers


  1. To make a html element, you need to do something like:

    var pElement = document.createElement('p'); //use different parameter to make different elements
    pElement.className = 'className';
    pElement.textContent = 'textContent';
    // and essentially you put it in the DOM
    document.body.appendChild(pElement);
    

    Now, you just need to make a for loop (for "data") and within each iteration make the p element and time element, and append them to the DOM.

    Login or Signup to reply.
  2. var jsonData = {
          "data": [
            {
              "fieldData": {
                "Message": "Message 1",
                "Timestamp": "04/14/2023 11:39:13"
              }
            },
            {
              "fieldData": {
                "Message": "Message 2",
                "Timestamp": "04/13/2023 10:02:18"
              }
            },
            {
              "fieldData": {
                "Message": "Message 3",
                "Timestamp": "08/19/2021 19:51:21"
              }
            }
          ]
        };
        
        var html = jsonData.data.map(function (item) {
          let div = document.getElementById("content");
        
          div.innerHTML +=  "<p class="from-them">" + item.fieldData.Message + "</p>n" +
                 "<time class="timestamp-to">" + item.fieldData.Timestamp + "</time>n";
        })
    <body>
        <div id="content">
    
        </div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search