Javascript - Use String As Object Reference
If I have a bunch of objects, and within these objects is the string 'id' (which is the same as the object name) how can I use this string to reference the object? Example: //These
Solution 1:
If your variables are defined on a global scope, the following works
window[ myObj.id ].data
If you are in a function's scope, things get a lot harder. Easiest way then is to define your objects in a specific namespace on window and retrieve the objects similar to the above code.
Solution 2:
Store test1 and test2 in a key-value collection (aka an object.) Then access it like:
collection[myObj.id].data
Solution 3:
If you want to refer to something using a variable, then make that something an object property, not a variable. If they are sufficiently related to be accessed in that way, then they are sufficiently related to have a proper data structure to express that relationship.
var data = {
test1: {
id: "test1",
data: "Test 1 test 1 test 1"
},
test2: {
id: "test2",
data: "Test 2 test 2 test 2"
}
};
Then you can access:
alert( data[myObj.id] );
Solution 4:
Great answers all, thanks for the help, in case any one finds this in future, this is how I'm going to use it:
var parent = {}
parent.test1 = {
id : "test1",
data : "Test 1 test 1 test 1"
}
parent.test2 = {
id : "test2",
data : "Test 2 test 2 test 2"
}
var myObj = null;
function setMyObj(obj){
myObj = obj;
}
setMyObj(parent.test1);
parent[myObj.id] = null;
//Test1 object is now null, not myObj!
Post a Comment for "Javascript - Use String As Object Reference"