如何检查对象中的每个属性是否为空 [英] How to check if every properties in an object are null
问题描述
我有一个对象,有时它像是{}
一样是空的,其他时候它将具有设置为null的属性.
I have an object, sometimes it is empty like so {}
other times it will have properties that are set to null.
{
property1: null,
property2: null
}
如何确定该对象内的所有属性是否为空? 如果它们全为空,则返回false.
How can I determine if ALL the properties within this object is null? If they are all null then return false.
此刻,我正在使用lodash检查对象只是{}
为空的第一种情况.但是我还需要介绍第二种情况.
At the moment I'm using lodash to check for the first case where the object is simply {}
empty. But I also need to cover the second case.
if (isEmpty(this.report.device)) {
return false;
}
return true;
推荐答案
您可以使用Object.values
将对象转换为数组,并使用every
检查每个元素.使用!
取反值.
You can use Object.values
to convert the object into array and use every
to check each element. Use !
to negate the value.
let report = {
property1: null,
property2: null,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
一个示例,其中某些元素不是null
An example some elements are not null
let report = {
property1: null,
property2: 1,
}
let result = !Object.values(report).every(o => o === null);
console.log(result);
文档: Object.values() , every()
这篇关于如何检查对象中的每个属性是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!