0

I'm attempted to create a simple array, inside of another array.

Excuse me, as I'm a bit new to this, but I am attempting to insert the following:

"m1":["username"]

into a empty array named:

var mg = {}

So that it looks like this,

var mg = {"m1":["username"]}

I attempted to insert it like so,

function insertPlayer(mid, user){
mg.push(mid = [user]);
}

insertPlayer("m1", "username")

I was using the push function, but it seems to completely ignore me.

This is what I want:

enter image description here

With the function I was using, I'm getting this:

enter image description here

If I could get it the way I want, I can easily grab the list of usernames inside 'm1' by easily calling mg["m1"]

I'm sure there is an easy fix for this, but I just can't find it. I've been researching for about 30 minutes and decided to ask here. Thanks!

2 Answers 2

1

mg is an object, not an array, it does not have .push method.

Instead of mg.push(mid = [user]);, it should be mg[mid] = [user];.

After that, mg.mid is an array, if you want to add new user to it, you could use .push,

mg[mid].push(user);

So the function will like below:

// pass mg as a parameter is better than use it as a global in function
function insertPlayer(mg, mid, user){
  if (mg[mid]) {
     mg[mid].push(user);
  } else {
     mg[mid] = [user];
  }
}
2
  • Thank you, this helped fix it but - rather than it saying "m1", it says 'mid'. Is there a way to fix this? imgbomb.com/i/d15/nu7b7.png Commented Aug 2, 2012 at 7:38
  • @Alex Check the code I added, use mg[mid] instead of mg.mid. Commented Aug 2, 2012 at 7:39
0
var mg = {'m1': []};

Then try mg[mid].push(user); instead of mg.push(mid = [user]);

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.