我有嵌套对象用户
let users = {
'0LsRDanmw1s1KBvZAAAC':
{
name: 'user1',
room: 'Lobby'
},
'Qvd9v0EStnwNe11mAAAD':
{
name: 'user2',
room: 'Music'
},
};
我希望获得room === 'Lobby'
let onlineUsers = ['user1'];
提前致谢
编辑: 很多好的解决方案谢谢你们!
答案 0 :(得分:0)
获取值,执行.filter()
然后.map()
。
let users = { '0LsRDanmw1s1KBvZAAAC': { name: 'user1', room: 'Lobby' }, 'Qvd9v0EStnwNe11mAAAD': { name: 'user2', room: 'Music' },};
var onlineUsers = Object.values(users)
.filter(u => u.room === 'Lobby')
.map(u => u.name);
console.log(onlineUsers );

.as-console-wrapper { max-height: 100% !important; top: 0; }

或者您可以获取值并执行.reduce()
。
let users = { '0LsRDanmw1s1KBvZAAAC': { name: 'user1', room: 'Lobby' }, 'Qvd9v0EStnwNe11mAAAD': { name: 'user2', room: 'Music' },};
var onlineUsers = Object.values(users)
.reduce((a, u) => (u.room === 'Lobby' ? [...a, u.name] : a), []);
console.log(onlineUsers);

.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

答案 1 :(得分:0)
您可以获取数组的值,根据需要进行过滤,并仅映射名称。
var users = { '0LsRDanmw1s1KBvZAAAC': { name: 'user1', room: 'Lobby' }, 'Qvd9v0EStnwNe11mAAAD': { name: 'user2', room: 'Music' } },
result = Object
.values(users)
.filter(({ room }) => room === 'Lobby')
.map(({ name }) => name);
console.log(result);

答案 2 :(得分:0)
Object.values
,filter
和map
的组合:
let users = {'0LsRDanmw1s1KBvZAAAC': { name: 'user1',room: 'Lobby' },'Qvd9v0EStnwNe11mAAAD':{ name: 'user2',room: 'Music' },};
const res = Object.values(users)
.filter( o => o.room === 'Lobby')
.map( o => o.name );
console.log(res);

答案 3 :(得分:0)
使用 ES8 Object.values()
获取对象的所有值,然后应用.filter
和.map
let users = {
'0LsRDanmw1s1KBvZAAAC':
{
name: 'user1',
room: 'Lobby'
},
'Qvd9v0EStnwNe11mAAAD':
{
name: 'user2',
room: 'Music'
},
};
var onlineUsers = Object.values(users).filter(el => el.room==="Lobby").map(el => el.name);
console.log(onlineUsers);
答案 4 :(得分:0)
我仍然喜欢简单的for
循环的旧学校,旧浏览器安全版本,所以为了完整起见:
var users = {
'0LsRDanmw1s1KBvZAAAC':
{
name: 'user1',
room: 'Lobby'
},
'Qvd9v0EStnwNe11mAAAD':
{
name: 'user2',
room: 'Music'
},
};
var lobbyUsers = [];
for (var prop in users) {
if (users.hasOwnProperty(prop)) {
if (users[prop].room === 'Lobby') {
lobbyUsers.push(users[prop].name);
}
}
}
console.log(lobbyUsers);