user1242574
user1242574

Reputation: 1267

Get object from array?

I'm working on a JavaScript chat app. I'm trying to retrieve chat messages from a history array. Currently I have 1 object in this array but there will be more objects.

When I stringify the array this comes out:

[[{"chatName":"Piet","time":"13:00","message":"asdasdasd"}],
 "14282568276220321","14282568276220321"]

In console it looks like this:

[Array[1], "14282568276220321", "14282568276220321"]
   0: Array[1]
      0: Object
         chatName: "Piet"
         message: "asdasdasd"
         time: "13:00"
        __proto__: Object
        length: 1
      __proto__: Array[0]
      1: "14282568276220321"
      2: "14282568276220321"
      length: 3
  __proto__: Array[0]

I would like to retrieve all messages from the array in a way that I can style it width css, like this for example per message:

<div id"messageContent">
  <b>Piet</b>
  <span>13:00</span>
  <p>asdasdasd</p>
</div>

Upvotes: 0

Views: 80

Answers (2)

ozil
ozil

Reputation: 7117

var array =[[{"chatName":"Piet","time":"13:00","message":"asdasdasd"}],"14282568276220321","14282568276220321"];
var html='';
var arrayObjects=array[0];
for (var i=0; i<arrayObjects.length; i++){
var object=arrayObjects[i];
html = '<div id="messageContent" + 'i'><b>object.chatName</b>
<span>object.time</span><p>object.message</p></div>'
}

Upvotes: 0

mohamedrias
mohamedrias

Reputation: 18576

You can get it using array notation [] and using object properties.

var array = [[{"chatName":"Piet","time":"13:00","message":"asdasdasd"}],"14282568276220321","14282568276220321"];

var objects = array[0]; // will give the first item in array
var object = objects[0]; // will erturn you first item in that inner array
object.chatName; // Piet
object.time; // 13.00
object.message; // message

to populate it in that dom:

var div = document.querySelector("#messageContent");
    div.querySelector("b").textContent = object.chatName;
    div.querySelector("span").textContent = object.time;
    div.querySelector("p").textContent = object.message;

Mostly you may desire to create those messages via loop:

 var array = [[{"chatName":"Piet","time":"13:00","message":"asdasdasd"}],"14282568276220321","14282568276220321"];
var div = document.querySelector("#messagecontent"),
     html = "";
      console.log(div);
    
array[0].forEach(function(object) {
   // you can create a wrapper div for this as well
     html +="<div>";
     html += "<b>"+object.chatName+"</b>";
     html += "<span>"+object.time+"</span>";
     html += "<p>"+object.message+"</p>";
     html += "</div>";
});
div.innerHTML += html;
<div id"messagecontent"></div>

Upvotes: 1

Related Questions