Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Multi Dimentional Array

I have created a multidimensional array for a jobs feed like so:

var jobs = [                
        ["JOB222" , "Painter"],                 
        ["JOB333" , "Teacher"],                 
        ["JOB444" , "Delivery Driver"],             
];

I can access the array using the index number

alert( jobs[2][1] ); // Alerts Delivery Driver

If I set the reference number manually, I can loop through the array to find a match.

var viewingJobRef = "JOB333";
for (var i=0;i<jobs.length;i++) {

    if (jobs[i][0] == viewingJobRef) {
      alert(jobs[i][1]); // This will alert Teacher
    }

}

So my question is, is it possible to access the array directly and not use a loop?

var viewingJobRef = "JOB333";
alert( jobs[viewingJobRef][1] );  // I want this to alert Teacher

Firefox error console says: jobs[viewingJobRef]is undefined, how do I do it?

like image 568
Scott Avatar asked Apr 01 '26 06:04

Scott


1 Answers

You want to use objects:

var jobs = {                
        "JOB222" : "Painter",                 
        "JOB333" : "Teacher",                 
        "JOB444" : "Delivery Driver"             
};

Access like this :

var viewingJobRef = "JOB333";
alert( jobs[viewingJobRef] );

OR

alert( jobs["JOB333"] );

OR

alert( jobs.JOB333 );
like image 158
YannPl Avatar answered Apr 03 '26 19:04

YannPl



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!