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.
Build a lookup table: An JS object as a key-value-map, where the keys are the ids and the values are the user objects. Then you can select/match an user by id in O(n)
.
var map = {};
for (var i=0; i<arr.length; i++) {
var site = arr[i].site,
users = arr[i].users;
for (var j=0; j<users.length; j++) {
users[i].site = site; // needed for finding a user's site
map[ users[i].idUser ] = users[i];
}
}
// Now,
> map[ 23 ]
{idUser:23, idSocket:"v8d9d0fgfs7d", name:"Barack H. Obama", site:48}
Can you structure your data so the user id is the key, instead of an array you have to loop over?
var data = {
45: { user: 'Fred' },
58: { user: 'Sam' )
};
var userId = 45;
data[userId].user // => 'Fred'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.