如何检查对象的有效性?

How to check the validity of an object?

我有以下对象:

{
     "title": {
         "type": null,
         "message": null
     },
     "first name": {
         "type": null,
         "message": null
     },
     "lastName": {
         "type": null,
         "message": null
     },
}

如何检查嵌套对象之一是否具有 type 属性.

的值 error(字符串类型)

如果对象之一具有 type 的值 error,我的方法 isValid() 应该 return 布尔值 false。

该对象在 useState 挂钩中使用如下:

const [validateObj, setValidateObj] = useState(sampleObj);

..我想用这个方法:

const isValid = (): boolean => {
  return // hmm?
};

以下应该符合您的要求:

const isValid = (): boolean => 
    Object.values(validateObj)             // get the list of values
          .every(o => o.type !== "error"); // check that no type is "error"

every 的文档:

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

由于您在 React 组件中使用它,因此您不希望该函数在每次渲染时都发生变化,而是仅在 validateObj 发生变化时才发生变化。为此,您可能需要查看 useCallback 挂钩的文档。