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 objects are tests - note the id's are the same as the object name

var test1 = {
    id : "test1",
    data : "Test 1 test 1 test 1"
}

var test2 = {
    id : "test2",
    data : "Test 2 test 2 test 2"
}


/* ----- My Function   ----- */

var myObj = null;

function setMyObj(obj){
   myObj = obj;
}

setMyObj(test1);

/* ----- My Function   ----- */

Now, if I call the following:

myObj.id;

The Result is "test1" (a string). If I want to use this to get the data from test1, how would I do so?

"myObj.id".data
[myObj.id].data

^^^

These don't work!

Cheers, Rich

share|improve this question

74% accept rate
1  
myObj.data should do the job. – Furqan Jun 19 at 14:04
Hey Furqan - that get's me myObj data - I want test1's data (which could have changed in the meantime)! – Richard Jun 19 at 14:13
feedback

4 Answers

up vote 2 down vote accepted

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.

share|improve this answer
feedback

Store test1 and test2 in a key-value collection (aka an object.) Then access it like:

collection[myObj.id].data
share|improve this answer
Fwiw, this is the solution I'm going with, but I think @sirko answer the question exactly how it was posed. – Richard Jun 19 at 14:15
feedback

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] );
share|improve this answer
feedback

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!
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.