Im trying to create a node.js chat application and when someone joins the chat room I want to push the last 100 messages to their browser. I have node.js adding each chat message as an object with the username and text of the message into an array. When node.js pushes the array of objects it looks like this.
[
[
{
"username": "Warren2",
"text": "test1"
},
{
"username": "Warren2",
"text": "test2"
},
{
"username": "Warren2",
"text": "test3"
},
{
"username": "Warren2",
"text": "hello"
}
]
]
I’m having trouble parsing that with jquery and I think jquery is throwing errors because the objects are inside an extra set of brackets. The code I’m using to create the array of objects is as follows:
// chat history
var history = [];
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
// we add the message to the chat history
var obj = {username:socket.username,text:data};
history.push(obj);
history = history.slice(-100);
});
Am I doing something wrong or is there a way to remove the extra set of brackets or parse this with jquery? When I log the history data node.js is sending to the browser to the console it looks like this:
[Object { username="Warren2", text="test1"}, Object { username="Warren2", text="test2"}, Object { username="Warren2", text="test3"}, Object { username="Warren2", text="hello"}, Object { username="Warren", text="test"}, Object { username="Warren", text="test again"}, Object { username="Warren", text="test"}, Object { username="Warren", text="Hey"}]
Found it in another stackoverflow post. Haven’t seen this being used before but after parsing the incoming data with
The above code worked perfectly.