如何检查所有相似子对象的errorState属性不为null?当前仅能获取对象键
检查所有子对象的errorState属性是否均不为null
没问题,我来给你几个简单直接的方案解决这个问题!首先假设你的父对象结构大概是这样的:
const parentObj = { astate: { errorState: null }, bstate: { errorState: "invalid input" }, cstate: { errorState: null } };
方案1:快速验证所有子对象是否符合要求
如果你只需要知道所有子对象的errorState是不是都不为null,可以用Object.values()结合every()方法:
// 验证所有子对象的errorState均不为null const allValid = Object.values(parentObj).every(child => child.errorState !== null); console.log(allValid); // 结果为false,因为astate和cstate的errorState是null
Object.values(parentObj)会把父对象里的所有子对象提取成一个数组every()方法会遍历数组,只要有一个子对象的errorState为null,就返回false;全部符合要求则返回true
方案2:找出所有不符合要求的子对象
如果你需要知道具体哪些子对象的errorState是null,可以用Object.entries()来同时获取键名和子对象:
// 筛选出errorState为null的子对象键名 const invalidStates = Object.entries(parentObj) .filter(([key, child]) => child.errorState === null) .map(([key]) => key); console.log(invalidStates); // 输出: ["astate", "cstate"]
Object.entries(parentObj)返回一个包含键值对的数组,比如[["astate", {...}], ["bstate", {...}]]- 先通过
filter()筛选出errorState为null的项,再用map()提取对应的键名
额外:处理可能的异常情况
如果父对象里可能存在非对象类型的属性(比如某个键对应的值是字符串或数字),直接访问errorState会报错,这时候可以加一层安全判断:
const allValid = Object.values(parentObj).every(child => // 先确保child是对象且存在,再检查errorState child && typeof child === 'object' && child.errorState !== null );
内容的提问来源于stack exchange,提问作者Black.Jack
相关产品推荐
相关产品推荐

