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
To make a html element, you need to do something like:
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.