简体   繁体   中英

Can I pass an object into a function that takes its fields as parameters?

I have a function that looks somewhat similar to the following:

foobar: function(arg1, arg2, arg3, ... argN) {
   // execute function
   // return result
}

In reality, this function takes a lot of arguments. I am not allowed to change the content of this function or the way it's built.

I also have an object:

inputObj: {
   arg1: val1,
   arg2: val2,
   // ...
   argN: valN
}

where the fields of this object match the parameters of the function foobar exactly -- in other words, the fields are spelt the same, they're added to the object in the same order, etc.

Does Javascript have an built-in function to either pass inputObj into the function foobar ? Alternatively, does Javascript have an elegant way for me to split up the inputObj object into its contents such that the values are passed into the function according to their keys?

One possible solution, for example, could be:

const arg1 = inputObj['arg1'];
const arg2 = inputObj['arg2'];
// ...
const argN = inputObj['argN'];

foobar(arg1, arg2, ..., argN);

but I'm looking for a way to avoid writing out the whole code block as such to make it easier to read.

Thanks in advance!!

You can use destructuring.

const {arg1, arg2, ..., argN} = inputObj;
foobar(arg1, arg2, ..., argN);

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