简体   繁体   中英

Apply an object's properties to the arguments of a function

Suppose I have a function (possibly from a 3rd party library, assume I can't change its definition), and an object with properties that match or overlap the function's arguments:

function fn(foo, bar, baz) { /* do stuff */ }
var obj = { foo: "yes", bar: 7, baz: false }

Is there a way to apply the objects properties as the functions arguments using some kind of destructuring or spread assignment, or some other ES6 feature, or am I stuck with specifying each argument seperately?

fn(...obj); // Doesn't work
fn(obj.foo, obj.bar, obj.baz); // Convoluted but works
fn.apply(null, obj.values()); // Might work if you're lucky

You could create a wrapper function for fn :

const myFn = ({foo, bar, baz}) => fn(foo, bar, baz);

And then your call simplifies to:

myFn(obj);

This is an ugly hack and should probably be avoided but it does work (even if the object's values aren't in the same order as the parameters).

 const STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg; const ARGUMENT_NAMES = /([^\\s,]+)/g; function getParamNames(func) { const fnStr = func.toString().replace(STRIP_COMMENTS, ''); let result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES); if(result === null) result = []; return result; } function fn(foo, bar, baz) { return {foo, bar, baz}; } const obj = { foo: "yes", baz: false, bar: 7 }; const result = fn(...getParamNames(fn).map(name => obj[name])); console.log(result);

Note: Credit for the getParamNames function goes to How to get function parameter names/values dynamically?

You should destructure the key-object pairs inside the function.

 const fn = (opts) => { const { foo, bar, baz } = opts; // Your function's "parameters" console.log({ foo, bar, baz }); } const obj = { PI: Math.PI, bar: 7, baz: false, foo: "yes" }; fn(obj);

The naive approach would be to call the function using the spread operator (or apply-null technique), but this does not guarantee that the key-value pairs within the object align with the expected order of the parameters.

 function fn(foo, bar, baz) { console.log(arguments); } const obj = { foo: "yes", bar: 7, baz: false }; fn(...Object.values(obj)); // or fn.apply(null, Object.values(obj))

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