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
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 Comments
mg[mid] instead of mg.mid.var mg = {'m1': []};
Then try mg[mid].push(user); instead of mg.push(mid = [user]);