0

I have a bunch of jQuery objects with a init method, so right now I have something like this

$.myobject1.init(somevar);
$.myobject2.init(somevar); 
$.myobject3.init(somevar);
$.myobject4.init(somevar);
$.myobject5.init(somevar); // somevar is the same var in all the calls

but I'm looking for a way to simply this code, something like this

var objectName = "myobject1"; // or any other object name
$. objectName .init(somevar);

thanks for the help! :-)

3
  • 1
    Does $[objectName].init() not work? Commented Oct 8, 2013 at 14:29
  • possible duplicate of How do I reference a javascript object property with a hyphen in it? Commented Oct 8, 2013 at 14:31
  • the answers look good, but if you do want to do it with strings, remember in javascript foo.bar == foo["bar"]. so $["myobject1"].init(somevar) should do what you want for the second code piece. Commented Oct 8, 2013 at 14:31

4 Answers 4

1

Since they are already jQuery objects you don't need $. and you can use .add() like this :

var object = myobject1.add(myobject2).add(myobject3).add(myobject4).add(myobject5);
object.init(somvar)
Sign up to request clarification or add additional context in comments.

Comments

1

Just use

$[objectName].init(somevar);

Comments

0

in javascript, all objects are maps. it's really weird, but it means you can do this trick:

var p = "mypropertyname";
var obj = {};
obj[p] = somevalue;

then, if you do:

console.log(obj.mypropertyname)

you'll get:

> somevalue

Comments

0

If you mean you want to loop through the names of your objects, then you should know that you can't combine strings with dot notation:

var someObj = {
    subObj: {
        a: 5
    }
};

someObj.subObj.a === 5;       // true
someObj."subObj".a === 5;     // throws error

But you can use strings with square bracket notation:

someObj["subObj"].a === 5;       // true

var propName = "subObj";

someObj[propName].a === 5;       // true

So you can use that to loop through your object names with a for loop, or you can use a jQuery method as suggested in other answers.

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.