1

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

2
  • 1
    myObj.data should do the job. Commented Jun 19, 2012 at 14:04
  • Hey Furqan - that get's me myObj data - I want test1's data (which could have changed in the meantime)! Commented Jun 19, 2012 at 14:13

4 Answers 4

4

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.

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

Comments

2

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

collection[myObj.id].data

1 Comment

Fwiw, this is the solution I'm going with, but I think @sirko answer the question exactly how it was posed.
2

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] );

Comments

0

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.