0

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.

1
  • you can get each object from the array, why do you have to change the way you put into array? Commented Nov 24, 2014 at 8:34

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

isn't there missing newuserData ?
@Dwza Yes and no, I omitted all of the logic on purpose :)
oh, i see... did not realised the //logic-comment :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.