I have been trying this fora a little while and cannot get it.
I have a piece of code to create an Array of an objects which is something like this :
var allUsers = new Array();
function addObjectToArray(userData){
colorCode = '#'+Math.floor(Math.random()*16777215).toString(16);
userImage = "avatar"+Math.floor(Math.random()*11)+".jpg";
newuserData = {};
newuserData[userData.userID] = {"nickName":userData.nickName,"SocketId":socket.id,"colorCode":colorCode,"userImage":userImage};
allUsers.push(newuserData);
}
So this function adds a new Object to array everytime it is called and after calling this function twice with different params i get an array something like this
[ { '886':
{ nickName: 'MOhan',
SocketId: '9AMRe2v2e-hWuMeBAAAC',
colorCode: '#d3af07',
userImage: 'avatar6.jpg' } },
{ '172':
{ nickName: 'Anil',
SocketId: 'a5VU5pCzWecMHM2FAAAD',
colorCode: '#22b913',
userImage: 'avatar4.jpg' } } ]
What i want instead is an object something like this :
{
'886':
{ nickName: 'MOhan',
SocketId: '9AMRe2v2e-hWuMeBAAAC',
colorCode: '#d3af07',
userImage: 'avatar6.jpg' } ,
'172':
{ nickName: 'Anil',
SocketId: 'a5VU5pCzWecMHM2FAAAD',
colorCode: '#22b913',
userImage: 'avatar4.jpg' }
}
What changes should i make to the code.
Easy, objects aren't technically pushed to but instead you define new keys on that object. Switch your Array for an object literal and just add the key to it.
var allUsers = {};
function addObjectToObject(userData) {
//logic
allUsers[userData.userId] = newuserData;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments