2

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?

1
  • 2
    Use an object instead of an array Commented Apr 9, 2014 at 13:26

2 Answers 2

10

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you, this works perfect, I'll use objects instead of arrays.
0

You may use objects:

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

And loop with:

for ( var i in jobs ) {...}

Or access directly like:

alert( jobs.JOB333 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.