简体   繁体   English

将数组键转换为数字node.js

[英]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? 有没有办法用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. 我找到了一种解决方法,方法是使用用户名创建第二个对象,它们指向用户对象的ID。 This might not work for other applications but it did it for mine. 这可能不适用于其他应用程序,但对我来说却适用。

CLOSED 关闭

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) : 现在,可以使用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: 假设您要获得一个对象数组,其实名是“ Peter”,并假设数据中有多个“ Peters”:

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

OUTPUT 输出值

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

DEMO CODE 演示代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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