1

I have a basic function taking an argument. I will use this argument to as index to access the array in JSON file. I want to take advantage of this argument instead of hard-coded inside the function. However, for some reasons, javascript is not return me the right value.

var obj = {
    "first":[
        ["aaaaa"],
        ["bbbbb"],
        ["ccccc"],
        ["ddddd"],
        ["eeeee"]                   
    ]
}

I have a javascript function to access the file.

function addElement(ID) {
    console.log(obj.ID);
}

and now if I use

addElement("first"); //this return me undefined. 

I do not want to explicitly mention obj.first in order to access the right JSON object. I would like to make it more generic so that the method can be re-used. Am I missing anything here?

Thanks...

1 Answer 1

3

JavaScript supports both dot notation and a property name literal (obj.foo), and brackets notation and a property name string (obj["foo"]).* In the latter case, the string can be the result of any expression.

So you'd need brackets notation, not dot notation:

function addElement(ID) {
    console.log(obj[ID]);
}

obj.ID accesses the property ID. obj[ID] accesses the property whose name is the string from the variable ID.


* Just for completeness: In ES6, it will support property name Symbols in brackets notation as well, but that's not relevant to your code.

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

1 Comment

omg..thanks for your answer..didnt this is just a property of JS..Thanks!

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.