I’m, by no means, JS fluent, so forgive me if im asking for some really basic stuff, but I’ve not being able to find a proper answer to my question.
Im writting my first Node.js (plus Extra Framework and Socket.io) app and Im having some fun setting up the server side of a FB-like messenger (surprise!!!).
So, let’s say I have this data structure to store online users(This is a JSON Array, but I’m not sure it is the best way to do it or should I go with Javascript Objects):
[
{
"site": 45,
"users": [
{
"idUser": 5,
"idSocket": "qwe87r7w8qwe",
"name": "Carlos Ray Norris"
},
{
"idUser": 6,
"idSocket": "v8d9d0fgfs7d",
"name": "John Connor"
}
]
},
{
"site": 48,
"users": [
{
"idUser": 22,
"idSocket": "qwe87r7w8qwe",
"name": "David Bowie"
},
{
"idUser": 23,
"idSocket": "v8d9d0fgfs7d",
"name": "Barack H. Obama"
}
]
}
]
What I want to do is to search in the array for x value given y. In this case, retrieving the idSocket knowing the idUser WITHOUT having to run through the array values.
So I have basically 2 questions: first, what would be the proper way to store users online? and secondly, how to find values matching with the values I already know (find the idSocket that has a given idUser).
I would like a pure JS approach(or using some of the tools given by Node, Socket.io or Express), but if that’s not possible then I can look for some JQuery.
EDIT
I took chovy’s advice and modified a little the structure, now it looks like this
{
45: { // site
05: { // userId
"name": "Carlos Ray Norris",
"socketID": "qwe87r7w8qwe"
},
06: {
"name": "John Connor",
"socketID": "v8d9d0fgfs7d"
}
},
48: {
22: {
"name": "David Bowie",
"socketID": "erv7e6v876vr"
},
23: {
"name": "Barack H. Obama",
"socketID": "brt877brtt87"
}
}
}
Thanks to Node.js, I can easily access to the data like this (I know both, the site and userId value) var socket = data[site]["05"].socketId. Im guessing this is done thanks to Node.js, but Im not completely sure.
Can you structure your data so the user id is the key, instead of an array you have to loop over?