array()函数返回一个对象

时间:2017-07-02 12:26:32

标签: javascript arrays node.js discord discord.js

我的discord.js有问题 我试图让所有拥有let gplayers = games_array[0].role.members角色的玩家,但因为它返回的对象类似于{"123" => GuildMember {}, "456" => GuildMember {} ...},我只需要"123""456"个对象我尝试使用let gplayers = games_array[0].role.members.array(),然后使用gplayers[i] m,但它不起作用 我试图检查出了什么问题,我发现gplayers是一个对象,即使我使用了array()函数。

console.log('Members: ', JSON.stringify(games_array[0].role.members, null, 4))记录Members: {}

如何将对象存储在数组中?

4 个答案:

答案 0 :(得分:0)

您可以循环访问键(在本例中为" 123"," 456"等)并将其值推送到新数组中。

let players = [];
let members = games_array[0].role.members;
for(key in members) {
    players.push(members[key]);
}

答案 1 :(得分:-1)

您可以使用for-in循环遍历返回对象的属性

var gplayers = games_array[0].role.members;
var key;
for (key in gplayers) {
    // do whatever you want here
    // you can access the key's associated value as gplayers[key]    
}

答案 2 :(得分:-1)

您可以在最近的引擎中使用Object.values

let players = Object.values(games_array[0].role.members)

答案 3 :(得分:-1)

我终于找到了解决方案:我使用了这种方法

collection.forEach(function(guildMember) {
  //guildMember is now a User object, and I can do everything using properties
  console.log(guildMember.user.username);
})

解决方案主题:Loop through Snowflake array