如何从数组动态生成函数形式的参数并传入其他函数
问题:如何将操作数组转换为函数调用参数列表?
我有一个任意长度的对象数组,结构如下:
[ { "operator": "sortBy", "value": "price" }, { "operator": "startAt", "value": "7" }, ... ]
其中operator对应从JS模块导入的函数名,模块结构类似:
{ sortBy: function() {}, startAt: function() {}, ... }
value是string或number类型的任意值。
我需要基于这个数组生成对应的函数调用(比如Utils.sortBy("price")、Utils.startAt(7)),并将这些调用结果作为参数传入另一个支持任意数量参数的函数,示例代码如下:
import * as Utils from "@externalPackage"; const filters = [ { "operator": "sortBy", "value": "price" }, { "operator": "startAt", "value": "7" } ] const anotherFunction = (arg1, arg2, ...) => ... // 该函数可接受任意数量的参数 const helperFunction = (arr) => { // 这里该如何处理filters数组,得到可直接传入anotherFunction的参数列表? } // 期望最终等价于 anotherFunction(Utils.sortBy("price"), Utils.startAt(7)) const result = anotherFunction(helperFunction(filters))
解决方案
核心思路
遍历操作数组,对每个元素完成三步操作:
- 通过
operator字段从Utils中取出对应的函数 - 传入
value调用该函数,得到执行结果 - 将所有结果收集为数组,最后用扩展运算符(
...)展开,作为目标函数的参数
完整代码实现
import * as Utils from "@externalPackage"; const filters = [ { "operator": "sortBy", "value": "price" }, { "operator": "startAt", "value": "7" } ] const anotherFunction = (...args) => { // 示例逻辑:可根据实际需求修改 return args; }; const helperFunction = (arr) => { return arr.map(item => { // 取出对应工具函数 const targetFn = Utils[item.operator]; // 调用函数并传入value,若需类型转换可在此处理(如Number(item.value)) return targetFn(item.value); }); }; // 用扩展运算符将数组展开为独立参数传入目标函数 const result = anotherFunction(...helperFunction(filters));
额外优化建议
- 容错处理:如果
Utils中可能不存在对应operator的函数,可添加判断避免报错:
const helperFunction = (arr) => { return arr.map(item => { const targetFn = Utils[item.operator]; if (typeof targetFn === 'function') { return targetFn(item.value); } // 可返回默认值或直接过滤掉无效项 return null; }).filter(Boolean); // 过滤掉非函数调用的无效结果 };
- 类型转换:如果
value需要从字符串转为数字(比如示例中的"7"),可在调用时转换:targetFn(Number(item.value)),根据实际业务需求调整转换逻辑。
内容的提问来源于stack exchange,提问作者Dmitriif
相关产品推荐
相关产品推荐

