简体   繁体   中英

How to create generic method in javascript to build json request according to inputs?

I have method that create Json request according to 3 input arguments:

function jsonRequest(_action, _data1, _data2){
  var jsonData = JSON.stringify({
        data:{
            action: _action
           ,data1: _data1
           ,data2: _data2   
        }
    });
 return jsonData;
}

What if I want to input unknown count of parameters, lets say 4.

So how my function should be to take care about?

Something like:

jsonRequest("103","blabla","bobob", ....);

It must be generic to handle any count of parameters.

In my example I didn't use angularjs, but you welcome.

Please, help,

Thank you,

Functions have a hidden array-like variable called arguments which contain everything that was passed into that function during invocation. It would be similar to:

function jsonRequest(){
  var _action = arguments[0];
  var _data1 = arguments[1];
  var _data2 = arguments[2];

  //the rest of the code here

}

You could loop over the arguments, and append to an object the data you need. You can set the first iteration to append _action , and the rest to append _dataN , where N is the index.

But arguments only contain values, no names. I suggest you pass in an object to your function instead.

function jsonRequest(data){
  return JSON.stringify({data : data});
}

jsonRequest({
  action : ...,
  data1 : ...,
  data2 : ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM