0

I'm working on existing Javascript code, which uses datasets stored in objects which are named data1, data2, etc. The numbers are IDs taken from a database.

Now, I need to write a little additional function which takes the IDs as input, then constructs the appropriate object name using that Id, and then passes that object to a function as a parameter.

So, something like:

function doStuff(id){
    var objname="data"+id;
    //now, I need to pass the object (not just the name) to a function
    someFunction(objname);    //this obviously doesn't work, because it just passes the object name as a string
}

So, how do I pass the actual object to the function, given that I have the object name?

The question sounds elementary, and I assume there's a method which does just this, but google doesn't seem to help.

7
  • 1
    This implied the object exists, right? You should construct a key-value array them to establish the relationship. Commented Feb 10, 2013 at 19:26
  • So, in other words, to test this example code, you'd need two lines like data1 = 'one'; and data2 = 'two';, right? Commented Feb 10, 2013 at 19:27
  • 1
    Yes, the object exists already. So creating an array with IDs as keys and objects as values, and then getting an array member by ID should work? Commented Feb 10, 2013 at 19:28
  • @phihag Not sure what you're trying to say - the test code obviously doesn't work, it's just an illustration of what I'm trying to do. Commented Feb 10, 2013 at 19:29
  • Yes that should work - try it! Commented Feb 10, 2013 at 19:29

2 Answers 2

1

Since the objects exist, you need a way to "find" them. I suggest you create a relationship between the string and the object using a key-value array - the key is the string, and the value is the object. You can then index the array with the string, and it will return the object.

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

Comments

1

Create an object and store in it keys like so:

var obj = {
    data0 : "example 1",
    data1 : "example 2"
}

Then you can access the properties like so:

function doStuff(id) {
    var key = "data" + id;
    someFunction(key);
}

someFunction(key) {
    return obj[key];
}

Comments

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.