Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to add array values to object property

Tags:

javascript

Following code is for socket.io server in node.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};

io.on('connection', function(socket){
  socket.on('game', function(data){
    gamename[data.gamename]=data.number; //problem is here 
  });
});

gamename=name of the game; number= user id;

  1. there can be more number of games;
  2. there can be more number of users per game

and I am emitting game event in the client side with some data (includeing gamename, and number)whenever a connection is established with the server. So whenever a new client connects to the server the game event is triggered in the server. In the game event in the server side I want to push "number" to the object property gamename(variable).

example:

var games={};

whenever there is a connection for example for the game poker with user id 34 I want to do var gamename='poker';

 gamename[gamename] -> I want this automatically created as array, or   anything, but I want to push user id's.

the resulting objecting should be.

games={'poker' : [34]};

If I one more user connects for poker with user id 45,

games={'poker' : [34, 45]};

and If a a user connects for game cricket with user 67

games={'poker' : [34, 45],'cricket' : [67]};

Initial object

games={};

after some connections(there can be n number of connections)

games={'poker' : [34, 45],'cricket' : [67]};

If my question is not clear I will explain it in detail if anybody asks. Thanks in advance

like image 631
scriptkiddie Avatar asked Mar 13 '23 13:03

scriptkiddie


1 Answers

Like this:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};

io.on('connection', function(socket){
  socket.on('game', function(data){
    gamename[data.gamename] = gamename[data.gamename] || [];
    gamename[data.gamename].push( data.number ); //no more problem 
  });
});
like image 93
Tudor Constantin Avatar answered Mar 16 '23 02:03

Tudor Constantin