如何将一个数组的任何项目的特定 属性 值与另一个数组的任何字符串值进行比较和验证?

How does one compare and validate a specific property value of any item of an array to any string value of another array?

我有一组从输入标签接收到的对象。我想比较对象中的特定值是否与数组匹配。 例如输入需要多个文件,但我需要它只是特定格式。 格式为 png 或 jpeg。 当我只上传一个文件时,下面显示正确,我希望它在一次上传多个文件时工作。

我想验证整个对象是否包含有效格式,如果所有文件都是有效格式,则上传文件,如果其中一个文件格式不匹配,则不上传文件已上传。

提前致谢。

target.files 给出 enter image description here

const IMAGE_TYPES = ['image/png', 'image/jpeg'];

const handleClick = ({target}) => {
  Object.keys(target.files).forEach((key) => {
    if (IMAGE_TYPES.includes(target.files[key].type)) {
      setIsInvalidImageFormat(false);
    } else {
      setIsInvalidImageFormat(true);
    }
  });
};

<input
   id='icon-button-photo'
   multiple
   onChange={handleClick}
   type='file'
/>

您可以通过以下方式获取值,将对象转换为数组:

Object.values(<yourObject>)

这将生成一个值数组,然后您可以比较这些值。这对您的用例有用吗?

To get the values or key first you need to convert it into array.
Actually you are accessing the key which you dont require you need to access the values and then comparing.

const IMAGE_TYPES = ['image/png', 'image/jpeg'];

const handleClick = ({target}) => {
  Object.values(target.files).forEach((value) => {
    if (IMAGE_TYPES.includes(target.files[value].type)) {
      setIsInvalidImageFormat(false);
    } else {
      setIsInvalidImageFormat(true);
    }
  });
};

<input
   id='icon-button-photo'
   multiple
   onChange={handleClick}
   type='file'
/>

Array.prototype.every as well as Array.prototype.some are the tools for any boolean based validation of array entries. It also might be easier / better readable to make use of Object.values instead of Object.keys ...

function setIsInvalidImageFormat(isAllValid) {
  console.log({ isAllValid });
}
const IMAGE_TYPES = ['image/png', 'image/jpeg'];

function handleClick({ target }) {
  setIsInvalidImageFormat(
    Object
      .values(target.files)
      .every(fileData =>
        IMAGE_TYPES.includes(fileData.type)
      )
  );
};
.as-console-wrapper { bottom: 0; }
<input
  id="icon-button-photo"
  multiple
  onChange="handleClick(event)"
  type='file'
/>
<!--
<input
   id='icon-button-photo'
   multiple
   onChange={handleClick}
   type='file'
/>
//-->