从数组中获取对象?

时间:2015-04-06 14:21:59

标签: javascript arrays object

我正在使用JavaScript聊天应用。我试图从历史数组中检索聊天消息。目前我在这个数组中有1个对象,但会有更多的对象。

当我对数组进行字符串化时,这就出现了:

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

在控制台中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]

我想以一种我可以设置宽度css样式的方式从数组中检索所有消息,例如每条消息:

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

2 个答案:

答案 0 :(得分:1)

您可以使用数组表示法[]并使用对象属性来获取它。

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

在那个dom中填充它:

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

大多数情况下,您可能希望通过循环创建这些消息:

&#13;
&#13;
 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;
&#13;
<div id"messagecontent"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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>'
}