Search code examples
javascriptobjectmultidimensional-arrayconstructorobject-literal

How to achieve this multidimensional array in the most efficient way?


I want to make this array using JavaScript:

    -----------------------------------------------
    |                     |         male          |
    |                     |-----------------------|
    |   rafael            |         single        |
    |                     |-----------------------|
    |                     |          22           | 
    |---------------------|-----------------------|
    |                     |         male          |
    |   jack              |-----------------------|
    |                     |         married       |      
    |                     |-----------------------|
    |                     |         34            |
    -----------------------------------------------

And after a lot of thinking about how to make it i just used this :

var arr = [];
for(i = 0 ; i < 2 ; i++){
    arr[i] = [2]
    for (j = 0; j < 3 ; j++){
        arr[i][1] = [3];
        arr[i][1][j] = "this is row :" + i + ", column : 1, row : " + j ;
        console.log(arr[i][1][j]);
    }
}

Is there any other way, using object constructors or object literals to achieve this ? Because i want to access it like that

obj["first row"]["third row in second column"]

I want the user to enter whatever values in each cell, and call it like this :

obj["rafael"]["age"];

Note that i don't know how many rows there'd be, i just put and arbitrary values there, and arbitrary cell names.


Solution

  • I wouldn't make it an array, but rather an object ... since you are using it like an object anyways. (If you aren't using integer indexes and the length property, you using the array like a basic object anyways. All arrays are objects, not all objects are arrays.)

    Replace null with the values you'd be using, of course. Or you can leave them as placeholders.

    var a = {
      "first row": {
        "first row in second column": null,
        "second row in second column": null,
        "third row in second column": null
      },
      "second row": {
        "first row in second column": null,
        "second row in second column": null,
        "third row in second column": null
      }
    }
    

    Ah, if it is going to be dynamic, then I'd do something like this:

    var folk = {};  // Our basic place holder.
    var person = {};  // The 'inner information' to populate.
    person.married = true;
    person.age = 41;
    person.address = "777 Heaven's Gate";
    folk["Jeremy J Starcher"] = person;
    
    // Next person
    person = {};
    person.gender = 'male';
    person.insurance = true;
    folk["John Doe"] = person;
    
    window.alert(folk["John Doe"]["gender"]);
    window.alert(folk["John Doe"].gender);