首页 > 解决方案 > 如何检查数组中的所有对象是否都具有某些属性?

问题描述

我需要确保我的数组中名为的所有对象都具有名为andnormalizedActions的某些属性:startTimeduration

if (this.normalizedActions.find(x => x.startTime !== null)
&& this.normalizedActions.find(x => x.duration !== null)) {
    console.log('all objects have these two properties')
}

即使我知道某些对象没有这些属性中的任何一个,我仍然会看到此处定义的控制台日志。

我究竟做错了什么?

标签: arraysecmascript-6

解决方案


.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具有某些属性。在您的示例中,您只检查属性是否不为空,这不足以说明它是否存在。


推荐阅读