[英]Cannot use object key to reference method in Javascript
I have a set of methods for validating input stored in a variable val
such that I can call them like val.email
or val["email"]
. 我有一套验证存储在变量
val
输入的方法,这样我就可以像val.email
或val["email"]
那样调用它们。 I'm trying to create a general function that will take an object and apply the validation function to each value based on the keys. 我正在尝试创建一个通用函数,该函数将接收一个对象并将验证函数基于键应用于每个值。 My attempt is as follows:
我的尝试如下:
const validateInput = data => {
let errors = {};
const keys = Object.keys(data);
keys.map(key => {
const error = val[key](data[key]);
errors = { ...errors, ...error };
});
return errors;
};
I get this error: 我收到此错误:
TypeError: val[key] is not a function
TypeError:val [key]不是函数
However, the following executes successfully: 但是,以下成功执行:
const validateInput = data => {
let errors = {};
const test = "firstName";
const errors = {...errors, ...val[test](data[test])};
return errors;
};
When I log keys I get an array of strings and when I log typeof key I also get string, so I don't understand why it will not work within the map function. 当我记录键时,我得到了一个字符串数组,当我记录typeof键时,我也得到了字符串,所以我不明白为什么它在map函数中不起作用。
Thanks in advance. 提前致谢。
Thanks to Jonas above I was able to figure it out. 感谢上面的乔纳斯(Jonas),我得以弄清楚。 I'm comparing two fields (password and password2) inside of one function.
我正在比较一个函数内部的两个字段(password和password2)。 The following code works:
以下代码有效:
const validateInput = data => {
let errors = {};
const keys = Object.keys(val);
keys.map(key => {
let error;
if (data.hasOwnProperty(key)) {
switch (key) {
case "password":
error = val[key](data[key], data[`${key}2`]);
break;
default:
error = val[key](data[key]);
break;
}
errors = { ...errors, ...error };
}
});
return { errors, isValid: isEmpty(errors) };
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.