0

I have a JSON object as follows

var jsonData = {
    getData1:function(id1, id2){
    },
    getData2:function(id1, id2){
    }
};

I have a method name (eg: getData1) & arguments (id1, id2) in separate variables. these are dynamic.

Manually I can call the method as follows

jsonData.getData1(id1, id2);

but I want to call a method dynamically with passing 2 arguments (id1, id2). what is the correct way to do it?

3 Answers 3

3

Remember that jsonData.getData1 is just a shortcut for jsonData['getData1'], but in the latter version, what you put inside the square brackets can be any expression, not just a literal. So you can do:

var methodName = "getData1";
jsonData[methodName](id1, id2);
Sign up to request clarification or add additional context in comments.

Comments

0

This might be a case for the call method attached to every function.

jsonData[methodName].call(id1, id2)

Comments

0

In JavaScript, an object's properties can be accessed easily via array notation as well. So, in your case:

jsonData.getData1(id1, id2);

and

jsonData['getData1'](id1, id2); 

behave in the same way. You can also do:

var methodName = document.getElementById('methodNameInput').value;
jsonData[methodName](id1, id2); 

methodName just needs to be a string.

More:

var ob = {
   foo: 'hello',
   bar: function(x) {
     return x+'!';
   }
 };

 console.log(ob['foo'] + ' ' + ob['bar']('world'));   // prints "hello world!"
 console.log(ob.foo + ' ' + ob.bar('world'));         // prints "hello word!"

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.