简体   繁体   中英

Javascript: How to add array values to object property

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 aa 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 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 
  });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM