You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查数组对象中所有answers属性是否全部为空?

实现方案

你需要判断所有answers数组是否全部为空,可通过以下两种方案实现,同时可以满足「所有answers全为空时返回false」的需求:


1. 纯ES6实现

直接使用原生数组的every方法遍历判断:

// 先判断是否所有answers都为空,全为空时返回true
const isAllEmpty = questions.every(item => item.answers.length === 0);
// 按需求取反,全为空时最终返回false
const result = !isAllEmpty;

2. Lodash实现

如果你项目中已经引入了Lodash,可以用更简洁的写法:

// 写法1:显式遍历判断
const isAllEmpty = _.every(questions, item => _.isEmpty(item.answers));
const result = !isAllEmpty;

// 写法2:用Lodash属性迭代器简写
const isAllEmpty = _.every(questions, ['answers', []]);
const result = !isAllEmpty;

原有代码问题说明

  • 原ES6写法的判断逻辑写反了,你写的!_.isEmpty(item.answers)是判断「所有answers都不为空」,所以只要有一个answers为空就会返回false,不符合你的需求。
  • 原Lodash写法的第二个参数是固定值!_.isEmpty('answers'),这个值永远为true,所以_.every永远返回true,完全没有实现判断逻辑。

内容的提问来源于stack exchange,提问作者Mo.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:24:03