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...
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 Symbol
s in brackets notation as well, but that's not relevant to your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.