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! :-)

juanp_1982
  • 917
  • 2
  • 16
  • 37
  • 1
    Does `$[objectName].init()` not work? – MDEV Oct 08 '13 at 14:29
  • possible duplicate of [How do I reference a javascript object property with a hyphen in it?](http://stackoverflow.com/questions/7122609/how-do-i-reference-a-javascript-object-property-with-a-hyphen-in-it) – Quentin Oct 08 '13 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. – Adam D. Ruppe Oct 08 '13 at 14:31

4 Answers4

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)
Anton
  • 32,245
  • 5
  • 44
  • 54
1

Just use

$[objectName].init(somevar);
Piotr
  • 671
  • 6
  • 17
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
Hassan Hayat
  • 1,056
  • 8
  • 20
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.

Ben Jackson
  • 11,722
  • 6
  • 32
  • 42