如何在此数据结构中找到空字符串



我需要在按下按钮时进行状态检查,根据结果,完成一件或另一件事。基本上,检查是否存在空的";值";字段,在这种情况下重定向到应用程序的另一个页面。有了代码,它看起来更好:

const [formData, setFormData] = useState<ISignUpFormData>({
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
});
const handleClick = async (e:any) => {
let canContinue = true;
const keys = Object.keys(formData);
keys.forEach(key => console.log()) // ??? keys is an array of strings, i need to access to "username".value to check if it is "" o not
}

值字段由受控输入填充

我的问题是:如何循环遍历一个值为​​是另一个物体吗?

您可以使用Object.values()find()。。。如果没有带有空字符串的条目,它将返回undefined

const [formData, setFormData] = useState<ISignUpFormData>({
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
})
const handleClick = () => {
const hasEmptyString = Object.values(formData).find(obj => obj.value === '');
//Returns object with empty string id there is any
//returns undefined if there is not entry with empty string
console.log(hasEmptyString);
}

或者,正如plichard在评论中指出的那样,你可以使用some(),它只会返回true/false,而不是返回具有空值的整个对象

const hasEmptyString = Object.values(formData).some(obj => obj.value === '');

您可以使用Object.entries获取键和值,然后检查其中是否有空字符串。

下面是一些天真的实现。

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

const object1 = {
username: { value: "", valid: true, unique: true },
email: { value: "", valid: true, unique: true },
password: { value: "", valid: true },
birthdate: { value: "", valid: true },
}
let hasEmptyString = false;
for (const [key, formKey] of Object.entries(object1)) {
if(formKey.value === ""){
hasEmptyString = true
break
}
}
if(!hasEmptyString){
// redirect to 
}
console.log(hasEmptyString)

最新更新