繁体   English   中英

如何比较数组中 object 的输入是否为空

[英]How can I compare if the inputs are empty or not of an object within an array

这些是输入

我试图循环一个数组并比较所有对象值是否不为空,如果所有输入(对象值)不为空 go 到下一步,否则显示错误。

单击“Agregar”按钮应该循环数组并查看输入是否为空'

这是代码:

const onAdd = () => {

 var match = false;
 for (let index = 0; index <= entities.length; index++) {   

  entities.map((value) => {
    if (
      value.entityName?.trim() == "" ||
      value.personInCharge?.trim() == "" ||
      value.emailPersonInCharge?.trim() == ""
    ) {
      match = true;
    } else {
      match = false;
    }
   
  });
}

if (match) {
  toast.error(
    "Completa todos los campos o marque la casilla de `Solo una compañia` "
  );
} else {
  entities.push(defaultFields);

  const newData = entities.map((d, index) => {
    return d;
  });

  setData({ entities: newData });
  setData({ ...dataNewChannel, entities: newData });
 
}

}

尝试这个

const form = [{}, {}, {}];

function validate(form) {
  const keys = Object.keys({
    entityName: '',
    personInCharge: '',
    emailPersonInCharge: ''
  });
  let errors = [];
  for (let i = 0; i < form.length; i++) {
    let hasError = false;
    for (let j = 0; j < keys.length; j++) {
      if (!form[i][keys[j]] || form[i][keys[j]].trim() === '') {
        hasError = true;
        errors.push(`form [${i}] ${keys[j]} is empty`);
        break;
      }
    }
    if (hasError) {
      break;
    }
  }
  return errors;
}

const err = validate(form); // [ 'form [0] entityName is empty' ]
if (err) {
  alert(err[0]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM