I have a situation where I wish to build an array that can be accessed via:
myArray['Foo'].push(myObj);
But I do not know how to create it from scratch. From what I had read I thought maybe the following would do it:
var myArray = new Array(new Array());
Problem is that it only lets me use integers to reference the myArray[]. If I ignore this limitation and try the following it errors saying it doesn’t have .push():
myArray[i].push(myObj);
I presume this is because myArray[i] is returning a string?
So my question is, how do I build a dynamic array where I reference the first dimension using strings and can then push and pop on the second dimension? Also if I take this approach, can I use push and pop for adding the string to the first dimension?
I thought about this a bit more before and wrote some code I thought may work, which it does.
var myArray = new Object();
var myObj = new Object();
var myObj2 = new Object();
var myObj3 = new Object();
myObj.name = "Harry";
myObj2.name = "Curly";
myObj3.name = "Moe";
myArray["first"] = new Array()
myArray["first"].push(myObj);
myArray["first"].push(myObj2);
myArray["first"].push(myObj3);
myArray["second"] = new Array()
myArray["second"].push(myObj2);
myArray["third"] = new Array()
myArray["third"].push(myObj3);
iterate(myArray, "first");
iterate(myArray, "second");
iterate(myArray, "third");
function iterate(array, name) {
for(i = 0, l = myArray[name].length; i < l; i++) {
console.log(" " + name + ": " + i + " value " + myArray[name][i].name);
}
}
Is the above the correct way to go about it?
I’m sure I’ve got some terminology problems with the above, let me know and I’ll edit it so it’s correct.
What you are calling
myArrayis not an array, it is an Object. Either of the following are acceptable:All of the following lines do the same thing; they create a key called “first” in the object “myObject” and store a new, empty array (into which you can push):
Now you can push into this array:
Here’s another way to write this from scratch:
So perhaps now the answers to your questions become more clear:
By making the “first”, or outer dimension be an object rather than an array.
Nope, but you can use