0

I have an array of objects and I want to generate messages on my page, how do I do that?

[{"message":"dwd","user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:42"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:38"},
 {"message":"dwd","user":"csac","date":"07.04.2021 20:38"}]

I want to generate on my page into one div every single message (each into its own div, user into div inside that div, etc.)

I've tried this:

data_arr = JSON.parse(data);
data_arr.map(function(comment){
                    
})

but I don't know what to do next.
This is how I want the result to look:

<div class='post'><div>message</div><div>user</div><div>date</div></div>
<div class='post'><div>message</div><div>user</div><div>date</div></div>
<div class='post'><div>message</div><div>user</div><div>date</div></div>
...

Thanks very much for answering.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
krystof18
  • 231
  • 3
  • 14
  • I want to generate post from this array like this ```
    message
    user
    date
    ``` -> this for every single item in array
    – krystof18 Apr 07 '21 at 19:54
  • 2
    *"I have an array of arrays"* <-- No, you have an array of objects. – Scott Marcus Apr 07 '21 at 19:57
  • If this is how you have it, there is no need to JSON.parse() it anymore. Because it already is an array (of objects). JSON.parse() must be called on strings. – Zoli Szabó Apr 07 '21 at 19:59
  • Why are you using `.map()`, which returns an array? You already have an array. Are you asking how to create elements, populate them and inject into the DOM? If so, please do some preliminary research on exactly that phrase and make an attempt. – Scott Marcus Apr 07 '21 at 19:59
  • Does this answer your question? [How to loop through an array containing objects and access their properties](https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties) Specifically, [this answer](https://stackoverflow.com/a/54731401/215552) – Heretic Monkey Apr 07 '21 at 20:07

2 Answers2

1

You could use a traditional for loop, or you could use forEach on the array of messages.
This uses forEach.

It uses innerHTML as discussed in comments, but it does it on a detached div so it's not causing page reflow until the completed div element is attached to the DOM.

// You've somehow acquired the new messages to be added
// Maybe you had to do a JSON.parse at some point, but now
// you have an Array of Objects
let msgs =
[{"message":"dwd one",  "user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd two",  "user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd three","user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd four", "user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd five", "user":"csac","date":"07.04.2021 20:42"},
 {"message":"dwd six",  "user":"csac","date":"07.04.2021 20:38"},
 {"message":"dwd seven","user":"csac","date":"07.04.2021 20:38"}];

// We need to add these new posts somewhere.
// They'll go in the "posts" section of the page.
const posts = document.getElementById('posts');
msgs.forEach(m => {
    // Create a new div for the post
    const newpost = document.createElement('div');
    // Set the class to "post" as desired
    newpost.classList.add('post');
    // Set the content of the new post, using string interpolation
    newpost.innerHTML =
      `<div class="message">${m.message}</div>
       <div class="author">${m.user}</div>
       <div class="date">${m.date}</div>`;
    // Append the new post to the "posts" section
    posts.appendChild(newpost);
 });
#posts .post div {
    display: inline-block;
}
/* This is just so you can see where the pieces lie */
.post div {
    margin-left: 5px;
    padding: 5px;
    border-left: 1px solid green;
}
<section id="posts">
</section>

This could be taken a step further and postpone attaching anything until the loop is complete. In that case it could even use .map to transform the original array of objects into an array of DOM elements, then .forEach on that array to attach them to the document.

In fact, let's try it that way...

// You've somehow acquired the new messages to be added
// Maybe you had to do a JSON.parse at some point, but now
// you have an Array of Objects
let msgs =
[{"message":"dwd one",  "user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd two",  "user":"csac","date":"07.04.2021 20:46"},
 {"message":"dwd three","user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd four", "user":"csac","date":"07.04.2021 20:43"},
 {"message":"dwd five", "user":"csac","date":"07.04.2021 20:42"},
 {"message":"dwd six",  "user":"csac","date":"07.04.2021 20:38"},
 {"message":"dwd seven","user":"csac","date":"07.04.2021 20:38"}];

// We need to add these new posts somewhere.
// They'll go in the "posts" section of the page.
const posts = document.getElementById('posts');
// Transform the message object into a DOM element (a div)
const newPosts =
    msgs.map(m => {
        // Create a new div for the post
        const newpost = document.createElement('div');
        // Set the class to "post" as desired
        newpost.classList.add('post');
        // Set the content of the new post, using string interpolation
        newpost.innerHTML =
          `<div class="message">${m.message}</div>
           <div class="author">${m.user}</div>
           <div class="date">${m.date}</div>`;
        return newpost;
    });
// Now attach all of the new "post" divs
newPosts.forEach(p => {
    posts.appendChild(p);
 });
#posts .post div {
    display: inline-block;
}
/* This is just so you can see where the pieces lie */
.post div {
    margin-left: 5px;
    padding: 5px;
    border-left: 1px solid green;
}
<section id="posts">
</section>
Stephen P
  • 14,422
  • 2
  • 43
  • 67
-1

In this case, you can use forEach. Here is how you would achieve your desired results:

<script type="text/javascript">
    
let messages = [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"},{"message":"dwd","user":"csac","date":"07.04.2021 20:46"},{"message":"dwd","user":"csac","date":"07.04.2021 20:43"},{"message":"dwd","user":"csac","date":"07.04.2021 20:43"},{"message":"dwd","user":"csac","date":"07.04.2021 20:42"},{"message":"dwd","user":"csac","date":"07.04.2021 20:38"},{"message":"dwd","user":"csac","date":"07.04.2021 20:38"}];



messages.forEach(function(comment){
    console.log(comment);
    // format: <div class='post'><div>message</div><div>user</div><div>date</div></div>
    document.documentElement.innerHTML += `<div class='post'><div>${comment["message"]}</div><div>${comment["user"]}</div><div>${comment["date"]}</div></div>`;
});






</script>
Krokodil
  • 1,165
  • 5
  • 19
  • 2
    *"The map function lets you manipulate each element in your array in turn."* <-- No, it doesn't. It returns a new array with whatever you want in it as it iterates over the original array. Also, you should never, never, never modify the DOM from within a loop, especially with `.innerhTML`. – Scott Marcus Apr 07 '21 at 20:00
  • Yes, but for example's sake this is what ive done, as i have no time for extensive styling and so on. – Krokodil Apr 07 '21 at 20:01
  • Ok, youre right actually, ill use foreach instead :) – Krokodil Apr 07 '21 at 20:02
  • You are not understanding or using `.map()` correctly. `.map()` returns a new array. It shouldn't be used when you just want to perform a task upon each iteration. That's what `.forEach()` is for. – Scott Marcus Apr 07 '21 at 20:03
  • yep, ive replied above ... and I changed my answer before I read this comment – Krokodil Apr 07 '21 at 20:04
  • You still are updating the DOM and using `.inerHTML` within a loop, which is very bad practice. `.innerHTML` should be completely avoided here and instead DOM objects should be created using the DOM API. Then, when the loop is done, inject the whole set of objects at once. – Scott Marcus Apr 07 '21 at 20:05
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/230869/discussion-between-alphahowl-and-scott-marcus). – Krokodil Apr 07 '21 at 20:05