Alexander
Alexander

Reputation: 155

Converting Array Keys to numbers node.js

I have the problem that i have an array like this :

var users = {
    'asidfjasd': {
       realname: 'John'  
    },
    'ggggggg': {
       realname: 'Peter'  
    }
}

And i want to access the users with

users[1]

to get

'ggggggg': {
       realname: 'Peter'  
}

Is there a way to do this with node.js?

EDIT

I have found a way to work around it by creating a second object with the usernames and them pointing to the id for the users-object. This might not work for other applications but it did it for mine.

CLOSED

Upvotes: 0

Views: 61

Answers (1)

Andy
Andy

Reputation: 63550

You should look more closely at the structures you want to use.

Objects can be accessible using their keys. Keys are unique and are unordered. I think your changed example is correct (I added in an extra property for use in a later example).

So...

var users = {
    'asidfjasd': {
       realname: 'John'  
    },
    'ggggggg': {
       realname: 'Peter'  
    },
    'aaaa': {
       realname: 'Peter'
    }
}

users.ggggggg // { realname: "Peter" }
users['ggggggg'] // { realname: "Peter" }

Now, it is possible to iterate over this using Object.keys(users):

var keys = Object.keys(users);

To log names to the console you could do this:

keys.forEach(function (el) {
  console.log(users[el].realname);
});

To return an array of names you could do this:

var names = keys.map(function (el) {
  return users[el].realname;
});

How about turning your current data into an array you can access by numerical index:

var arrayOfObjs = keys.map(function (el) {
  return { socketname: el, realname: users[el].realname };
});

OUTPUT

[
  { "socketname": "asidfjasd", "realname": "John" },
  { "socketname": "ggggggg", "realname": "Peter" }
]

You can then use array methods to pull out the information you want from the objects. Say you want to get an array of objects where the realname is "Peter" assuming multiple "Peters" in the data:

var peters = arrayOfObjs.filter(function (el) {
  return el.realname === 'Peter';
});

OUTPUT

[
  { "socketname": "ggggggg", "realname": "Peter" },
  { "socketname": "aaaa", "realname": "Peter" }
]

DEMO CODE

Upvotes: 2

Related Questions