Objects em javascript

Asked

Viewed 71 times

1

I’m having some problems with Objects while using them in Node js , I need an object like this :

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

However as I am using Node , I need to take these values dynamically by index( que é o [client.id]), remembering that the data are inserted dynamically and consumed also dynamically, and the way to get a value of this Object would be: user.[client.id].nome Any idea how to fix this ? client.id is the socket-generated ID

  • 1

    Friend, it was not clear what is your problem. And about Arrays... your code has no Array, only objects.

  • Our ... thousand excuses I will edit , I researched so much the whole day that I had array in my head

  • No problem... I believe the @bfavaretto answer is what you want.

2 answers

2


I think you want something like that, no arrays, just objects:

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

Testing:

var dados = clients[client.id]
  • To see what it is to be completely priced kkkkkkkkkkkk, I’m researching all day man , believe me I’m more than 6 hours researching , and nothing kkkkkk, thanks my friend was exactly that ... saved me

0

What you’re trying to do is 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;

So that you can take ALL customers from your 'index', you would do the following:

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

console.log(clientsArray);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.