Objects in javascript

1

I'm having some issues with Objects by using them in node js, I need an Object like this:

var clients = {};
var user = { 
    [client.id] : {
                    'nome': 'osvaldo', 
                    'sala': 'B1'
                  }
};
clients.push(user);

But as I'm using the node, I need to get these values dynamically by the index (which is the [client.id]), remembering that the data is dynamically inserted and dynamically consumed, and the way to get a value from that object would be: user.[client.id].nome Any idea how to solve this? the client.id is the ID generated by the socket

    
asked by anonymous 10.07.2017 / 20:02

2 answers

2

I think you want something like this, with no arrays, only objects:

var clients = {}; 
clients[client.id] = {
    'nome': 'osvaldo', 
    'sala': 'B1'
}; // repetir bloco para demais clientes

Testing:

var dados = clients[client.id]
    
10.07.2017 / 20:28
0

What you are trying to do is to use an object as an index for the client objects, which would look like this.

var clients = {};
var client = {id: 1, nome: 'Lucas', sala: 'B1'};
clients[client.id] = client;

In order for you to catch ALL clients from your 'index', you would do the following:

var clientsArray = [];
Object.keys(clients).forEach(function(key) {
  clientsArray.push(clients[key]);
});

console.log(clientsArray);
    
10.07.2017 / 21:20