Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript multidimensional arrays with alphanumeric keys

This seems to be a common source of confusion from what I've seen, and apparently I'm no exception. I've read a few tutorials on this, and I still can't quite get my head around it. From what I can gather, Arrays are objects in Javascript, just like Strings and other variable types. But I still don't get how that helps me declare a multidimensional array with alphanumeric keys.

In PHP I can simply write:

$calendar = array();

foreach ($schedule->currentExhibitions as $key) {
    $calendar[$key["ExhibitionID"]]["startDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
    $calendar[$key["ExhibitionID"]]["endDate"] = date("Y,n,j", strtotime($exhibition["StartDate"]));
} 

But in Javascript trying something similar will create errors. Should I create an Array and fill it will Objects? If so, how would I go about doing so? Or should I just use an Object entirely and skip having any sort of Array? (If so, how do I create a multidimensional Object?)

Sorry for the newbish quesion!

like image 606
Chuck Le Butt Avatar asked Sep 14 '26 16:09

Chuck Le Butt


2 Answers

If your keys are strictly numerical and ordered starting at zero, then an array makes sense and you can use square bracket notation just like you would in php, although you will need to initialize sub-arrays if you want to have multiple dimensions :

var myArray = [];
myArray[0] = [];
myArray[0][0] = "something interesting";

If your keys are not numerical, ordered and starting at zero, then you should use an object (all keys are strings), which still allows the square bracket notation :

var myObject = {};
myObject["1A"] = {};
myObject["1A"]["3B"] = "something interesting";
like image 176
Frances McMullin Avatar answered Sep 17 '26 05:09

Frances McMullin


In Javascript, an array is an object, who's keys are numerical, sequential, indexes.

As soon as you want to use alpha-numerica (aka strings) keys, you use a regular object.

In JS to do what you want, you'd do the following (using more or less your php code).

var calendar = {};

Object.keys(schedule.currentExhibitions).forEach(function(key) {
  var ex = schedule.currentExhibitions[key];

  calendar[ex.exhibitionId] = calendar[ex.exhibitionId] || {}; //if the key doesn't exist, create it.
  calendar[ex.exhibitionId].startDate = date(); //some js date function here
  calendar[ex.exhibitionId].endDate = date(); //your js date function here
});
like image 38
Alan Avatar answered Sep 17 '26 06:09

Alan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!