0

How do you access a key named "foo" of the 5th element of an array that is the 2nd element of another array that is the value of a hash key named "baz"?

can you provide the basic examples?

4
  • Associative arrays don't exist in JavaScript. You'll have to use objects instead { foo: "bar" }, only don't expect properties to always have the same "index" in an object. Commented May 28, 2013 at 15:58
  • 1
    JavaScript doesn't have associative arrays! It has (numeric) arrays, and objects. You can make an object: {foo: "bar", baz: "foobar"}, but they are unordered. Commented May 28, 2013 at 15:59
  • JS Object Commented May 28, 2013 at 15:59
  • It might be helpful if you could demonstrate in pseudocode or PHP the functionality you'd like to see. Your written-out description is a bit difficult to follow. Commented May 28, 2013 at 16:02

2 Answers 2

1

You want to use an object:

var obj = {
   foo: {
      bar: "yo"
   }
}
console.log(obj["foo"]["bar"]);

// Or you could do this

var obj = {};
obj["foo"] = {};
obj["foo"]["bar"] = "yo";
console.log(obj["foo"]["bar"]);

Note the order of an object is not guaranteed and can change depending on the interpreter / compiler.

An array in JavaScript is just an object with numerical indices (With some specific methods - see comment below). In fact pretty much everything in JavaScript is an object.

Sign up to request clarification or add additional context in comments.

1 Comment

Array's have a bunch of methods (e.g. indexOf) and properties (e.g. length) that you don't get on plain objects.
1

How do you access a key named "foo" of the 5th element of an array that is the 2nd element of another array that is the value of a hash key named "baz"?

variableName["baz"][1][4]["foo"];

Would get you "The value here" from

var variableName = { baz: [0, [0, 1, 2, 3, { foo: "The value here" }]] };

and here's a jsFiddle to play with

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.