简体   繁体   中英

javascript how to convert function parameters to object

I have function below and would like to convert parameters to object where parameters same name as key and value

functionA(name, callback, param1, param2, ....paramN)
{
var params = {'param1': param1,.....};
   $.ajax(... data: params.....);
}

My guess based on how this is worded (will edit if further details are provided):

If you're in an environment where ES6 is supported or you can transpile your code via babel or some other transpiler, you could write it like so:

function functionA(name, callback, ...params) {
  const paramsObj = params.reduce((params, param) => {
    return Object.assign(params, {[param]: param});
  }, {});
  $.ajax({data: paramsObj});
}

functionA(null, null, 'a', 'b'); // paramsObj will be: {a: 'a', b: 'b'}

Edit: If instead the OP wants the keys to be param1 , param2 , etc.:

function functionA(name, callback, ...params) {
  const paramsObj = params.reduce((params, param, i) => {
    return Object.assign(params, {[`param${i + 1}`]: param});
  }, {});
  $.ajax({data: paramsObj});
}

functionA(null, null, 'a', 'b'); // paramsObj will be: {param1: 'a', param2: 'b'}

One way you can do is

function a(p1, p2, p3) {
    a = {
        [p1]: p1,
        [p2]: p2,
        [p3]: p3,
    }
    console.log(a, 'a')
    // Gives you
    // {a: "a", b: "b", c: "c"}
}

a('a', 'b', 'c')

Combining with Scott Rudiger's Solution, you can do something as

function functionA(name, callback, ...params) {
    var p = params.reduce((obj, item) => {
        return obj[item] = item
    }, {})
    console.log(p)
    // Gives you
    // {dd: "dd", ee: "ee", ff: "ff", gg: "gg"}
}

functionA('pp', 'cc', 'dd', 'ee', 'ff', 'gg')

If i understood correctly, this is what you need.

let fnStr = arguments.callee.toString(),
    argNames = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(/([^\s,]+)/g), //argNames is a list of parameter names
    obj = {};
for(let i= 0; i < arguments.length ; i ++) {
    obj[argNames[i]] = arguments[i]
}

Go for rest parameters syntax and Array.reduce() to return object if you support ES6:

 function A(name, callback, ...params) { const result = params.reduce((obj, item,i) => { obj["param"+(i+1)] = item; return obj; }, {}) console.log(result); } A("name","callback","param1",2,"whatever","param4"); A("name","callback","param1"); 

The old way

 function A(name, callback, param1) { var params = {}; var n = 2; while( n < Object.keys(arguments).length ){ params["param"+(n-1)] = arguments[n]; n++; } console.log(params); } A("name","callback","param1",2,"whatever","param4"); A("name","callback","param1"); 

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