简体   繁体   中英

Add/change values in Object Javascript

I have an object named clients.

var clients = {"username" : test, "socket": asdasdkje3sf};

But I want to add some more clients. If I add an client on the following way:

clients = {
  "username" : username,
  "socket": socket.id
};

It gets overwritten every time I add a new value. I have tried it on this way:

clients += {
  "username" : username,
  "socket": socket.id
};

If I do console.log(clients) it seems to work but it returns [object][object][object][object] .

How can I read the objects? And is this the best approach to do this?

Thank you in advance!

How can I read the objects? And is this the best approach to do this?

Use an array, instead of an object.

var clients = [{"username" : test, "socket": asdasdkje3sf}];

Instead of adding via ++ , use push

clients.push({
  "username" : username,
  "socket": socket.id
});

You need to use a array data structure where you can push each object for clients . The way you are doing is incorrect as it concatenate the object with another object which result in invalid JSON object.

 var clients = []; clients.push({ "username" : 'username1', "socket": 'socket.id1' }); clients.push({ "username" : 'username2', "socket": 'socket.id2' }); console.log(clients); 

You probably want an array of objects (clients).

var clients = [{"username" : test, "socket": asdasdkje3sf}];

This way you can easily push new clients to it.

var newClient = {"username": "another name", "socket": "foobar"};
clients.push(newClient);

push() is an array method provided by JavaScript .

To read or display and object use,

console.log(clients.username + "|" + clients.socket)

Add to above answers to add objects to an array, you can also use concat instead push if you are planning to merge more than two arrays. The difference is 'push' updates the same array, 'contact' merges and returns a new array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM