如何遍历带自定义索引键的对象,筛选有值项并返回expr?
问题:筛选JavaScript对象时无法排除value为空或undefined的项
你拥有如下JavaScript对象requestArr,每个子对象包含value和expr属性:
var x = 12345 var y const requestArr = { oj: { "value": x, "expr": "testX" }, st: { "value": y, "expr": "testY" }, };
需求是遍历该对象,检查每个子对象的value值,仅当value存在(非空、非undefined)时返回对应的expr值。但你当前的筛选逻辑存在问题,仍会返回value为undefined的expr:
for (const [index, key] of Object.keys(requestArr).entries()) { if (requestArr[key].value !== '' || requestArr[key].value !== undefined) { console.log(requestArr[key].value) } }
错误原因
你的条件判断用了||(逻辑或),这意味着只要value不等于空字符串或者不等于undefined,条件就成立。但任何值都不可能同时等于空字符串和undefined,所以这个条件永远为true,自然会保留所有项。
修正方案
把逻辑运算符换成&&(逻辑与),这样只有当value既不是空字符串也不是undefined时,条件才成立。同时按需求返回expr值,而非value:
精准筛选(仅排除空字符串和undefined)
for (const [index, key] of Object.keys(requestArr).entries()) { const item = requestArr[key]; if (item.value !== '' && item.value !== undefined) { console.log(item.expr); // 返回符合条件的expr } }
简洁筛选(排除所有falsy值)
如果你的业务场景中,value为0、false、null等falsy值也需要排除,可以用更简洁的写法:
for (const [index, key] of Object.keys(requestArr).entries()) { const item = requestArr[key]; if (item.value) { console.log(item.expr); } }
内容的提问来源于stack exchange,提问作者David Garcia
相关产品推荐
相关产品推荐

