Reputation: 75
I have a global variable var room = {}
when i create a rooms it will go there and i will have the object like this
{
'4bea542f-147c-4763-ab1c-bb6c40b1392e': {
private: false,
users: {
btrJ7946MkjFSz_zAAAA: [Object],
'qe_1igD7Q-RbDWc1AAAC': [Object]
},
gameS: false,
nextUser: 'btrJ7946MkjFSz_zAAAA',
timer: null,
round: 0,
winner: false,
alreadyGuess: [],
timerStartedAt: 0,
settings: { gameStarted: false, time: null }
},
'e6ea6785-e522-4b8c-aeb8-b2551e89c895': {
private: false,
users: {
'n5BODsuqAWb5Y-WAAAAD': [Object],
paf4cWgX08Qi_8m5AAAE: [Object]
},
gameS: false,
nextUser: 'n5BODsuqAWb5Y-WAAAAD',
timer: null,
round: 0,
winner: false,
alreadyGuess: [],
timerStartedAt: 0,
settings: { gameStarted: false, time: null }
}
}
How can i access these objects with different names like '4bea542f-147c-4763-ab1c-bb6c40b1392e' and maybe get the ones with values private = false
Upvotes: 1
Views: 50
Reputation: 35684
Depends what you want to accomplish, striclty speaking to your question Object.values()
is probably the easiest, but it won't keep the key, which you might be interested in keeping.
to get the keys, use keys
var publicRoomsIds = Object.keys(rooms).filter(function (key) {
var room = rooms[key];
return (room.private === false);
});
to get the values (without keys) use values
var publicRooms = Object.values(rooms).filter(function (room) {
return (room.private === false);
});
var rooms = {
"4bea542f-147c-4763-ab1c-bb6c40b1392e": {
private: false,
},
"e6ea6785-e522-4b8c-aeb8-b2551e89c895": {
private: true,
},
"e6ea6785-3321-4b8c-aeb8-b2551e89c895": {
private: false,
},
"e6ea6785-7663-4b8c-aeb8-b2551e89c895": {
private: true,
},
};
var publicRoomsIds = Object.keys(rooms).filter(function (key) {
var room = rooms[key];
return (room.private === false);
});
var publicRooms = Object.values(rooms).filter(function (room) {
return (room.private === false);
});
console.log(publicRoomsIds);
console.log(publicRooms);
Upvotes: 2
Reputation: 89214
You can filter
over Object.values
.
const o = { '4bea542f-147c-4763-ab1c-bb6c40b1392e': { private: false, users: { btrJ7946MkjFSz_zAAAA: [Object], 'qe_1igD7Q-RbDWc1AAAC': [Object] }, gameS: false, nextUser: 'btrJ7946MkjFSz_zAAAA', timer: null, round: 0, winner: false, alreadyGuess: [], timerStartedAt: 0, settings: { gameStarted: false, time: null } }, 'e6ea6785-e522-4b8c-aeb8-b2551e89c895': { private: false, users: { 'n5BODsuqAWb5Y-WAAAAD': [Object], paf4cWgX08Qi_8m5AAAE: [Object] }, gameS: false, nextUser: 'n5BODsuqAWb5Y-WAAAAD', timer: null, round: 0, winner: false, alreadyGuess: [], timerStartedAt: 0, settings: { gameStarted: false, time: null } } };
const res = Object.values(o).filter(x => !x.private);
console.log(res);
.as-console-wrapper{top:0;max-height:100%!important}
If you also want the key, you could use Object.keys
or Object.entries
.
Upvotes: 0