arrays - 如何检查数组中的所有对象是否都具有某些属性?
问题描述
我需要确保我的数组中名为的所有对象都具有名为andnormalizedActions
的某些属性:startTime
duration
if (this.normalizedActions.find(x => x.startTime !== null)
&& this.normalizedActions.find(x => x.duration !== null)) {
console.log('all objects have these two properties')
}
即使我知道某些对象没有这些属性中的任何一个,我仍然会看到此处定义的控制台日志。
我究竟做错了什么?
解决方案
.find()
找到数组的第一个匹配元素,因此在您的情况下,如果只有一个对象具有startTime
并且一个(不是相同duration
的事件)具有条件为真。尝试.every()
:
if (this.normalizedActions.every(x => x.hasOwnProperty('startTime') && x.hasOwnProperty('duration'))) {
console.log('all objects have these properties');
}
另外,请注意,我曾经Object.hasOwnProperty()
确定 是否x
具有某些属性。在您的示例中,您只检查属性是否不为空,这不足以说明它是否存在。
推荐阅读
- python - 使用 pyinstaller 摆脱 chromedirver 控制台窗口
- jquery - 如何在 javascript/jquery 中将 id 添加到 data-id 元素
- express - 我没有收到提交带有详细信息(姓名、电子邮件、消息)的表单的发件人的电子邮件?
- android - BackPress 返回空白活动
- python - 将带有数字的文件复制到另一个带有这些数字的文件
- url - Google Analytics 中显示的页面路径错误
- angular - Angular6 应用程序无法在 IE 上运行,但在其他浏览器上运行良好。SCRIPT1002:语法错误 vendor.js (69467,1922)
- performance - 性能测试和 API 测试不在同一个框架中一起工作
- php - php-rql 选择命令
- php - 如何使用 Join On 更新 sql php 上的数据?