I have 2 or more objects in Main Object. How can I find one object againt this key value.
{
"0": {
"component": "AWAY",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
},
},
"1": {
"component": "PHONE_BOTH",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
}
},
"2": {
"component": "MEETING_ROOM",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": true,
"image": ""
}
}
}
I just want to get one object where inRoom = true
CodePudding user response:
It is not recommended to index an object with numeric keys. Use an array instead then you can use filter directly on the array
const arr = [{
"component": "AWAY",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
},
},
{
"component": "PHONE_BOTH",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": false,
"image": ""
}
},
{
"component": "MEETING_ROOM",
"currentUser": {
"id": 1,
"userName": "abc",
"inRoom": true,
"image": ""
}
}
]
console.log(arr.filter(({currentUser}) => currentUser.inRoom === true))
CodePudding user response:
You should convert your dictionary to an array and then find the object by a specific criteria using the find()
array method. See implementation:
// usersDict is the given Main Object
// convert usersDict to array of user objects
let usersArray = Object.values(usersDict);
// find user which has inRoom flag true
let userInRoom = usersArray.find(o => !!o.currentUser.inRoom);