Javascript multidimensional arrays with alphanumeric keys

arrays, javascript, multidimensional-array, object

Solution

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
});

Problem

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!

Original source