0

Possible Duplicate:
How do I dynamically call a JavaScript object’s method

I have function for different properties

setCar : function() {}
setBike : function() {}
setAirPlane : function (){}

I have object in format key value

var json = { Car : "Car1",
             Bike : "Bike1",
             AirPlane  : "test1" }

I want to call to the set function in dynamic way according to the object values:

 updateProperties : function(json) {        
 for ( var property in json) {
     //set + property (AdditionalProperties[property])
 };   

in the property I have the name of the function(Car,Bike,AirPlane) and in AdditionalProperties[property] I have the value of the property ( Car1,Bike1,test1.

Is it possible to do it ?

Community
  • 1
  • 1
user1365697
  • 5,819
  • 15
  • 60
  • 96

2 Answers2

4

Why not? It is possible to do:

for (var property in obj) {
    typeof funcContainer["set" + property] === "function"
      && funcContainer["set" + property](obj[property]);
}

Where funcContainer is:

var funcContainer = {
    setCar : function() {},
    setBike : function() {},
    setAirPlane : function() {}
};
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

If

objWithFuncts = {
...
setCar : function() {}
setBike : function() {}
setAirPlane : function (){}
...
}

Than you can do:

 updateProperties : function(json) {        
 for ( var property in json) {
       if(json.hasOwnProperty(property) && objWithFuncs["set" + property])
           objWithFuncs["set" + property](AdditionalProperties[property])
 }; 

Just remember that you can access any property of an object using index, like: obj["propName"] which is equal to obj.propName

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • 1
    There is no need in `hasOwnProperty` here. – VisioN Jan 31 '13 at 12:32
  • Can I wrote : updateProperties : function(json) { for ( var property in json) { this.["set"+ property](AdditionalProperties[property]) }; – user1365697 Jan 31 '13 at 12:38
  • if you call it like `objWithFuncs.updateProperties(json); ` than yes, but you have a mistake: `this.["set"+ property]` should be simply `this["set"+ property]` (no dot after this) – Viktor S. Jan 31 '13 at 12:41
  • @VisioN yes, with example `json` object - it is not required, but as for me, it is better to put it there - who knows how that object is created exactly? – Viktor S. Jan 31 '13 at 12:45