1

I'm trying to access a particular array by it's index within an object within an object (sorry, this may be the wrong terminology).

var person = {
 name: ["Tom", "Mike", "Sally"],
 hair: {
 style: ["bob", "weave", "mullet"],
 length: ["long","short","medium"]
 }
}
getDetail(length);
function getDetail(det) {
 var answer = person.hair.det[1];
 console.log("Hair " + det + " is " + answer) //outputs: "Hair length is long"
}

When I do this, I am getting an error of "Can't read property '1' of undefined". Which tells me it isn't passing the 'det' variable correctly. If I take that out and put length instead, it works.

What am I missing?

Thanks!

asked Apr 23, 2014 at 21:14

2 Answers 2

4

The problem is that in your case you should be passing a string or a variable to your getDetail() function (length by itself is none, as it is not defined previously, nor is quoted), also there's the fact that if you want to use a variable to indicate the property/key of an object, you should use this type of syntax: object["property"]. You can change your code to:

getDetail('length');
function getDetail(det) {
 var answer = person.hair[det][1];
 console.log("Hair " + det + " is " + answer) //outputs: "Hair length is long"
}
answered Apr 23, 2014 at 21:17
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I hate it when it's a little mistake like this. Darned technicalities!
0

When you say getDetail(length), that's looking for a variable called length, and passing it into the function. Since it doesn't exist, the function gets undefined.

HOWEVER, when you write "myObjectVariableName.etcetera", it will specifically look for an index called "etcetera" - so it won't even be using your det argument - it's instead looking for the "det" index.

You can, instead, write either of the following.

myObjectVariableName["myIndexName"]
var myString = "myIndexName";
myObjectVariableName[myString]

Both of those will both have the same result.

So, to get the expected result, what you want to do is pass the string "length" into getDetail, and then replace .det with [det] (darkajax seems to have written what I was going for, but I'm hoping my explanation also helps make sense of why it wasn't working)

answered Apr 23, 2014 at 21:20

1 Comment

Thank you! This plus darkajax's comments explained/solved my problem.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.