How to check if every properties in an object are null

泪湿孤枕 提交于 2020-02-04 08:39:45

问题


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
}

How can I determine if ALL the properties within this object is null? If they are all null then return false.

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;

回答1:


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);

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);

Doc: Object.values(), every()




回答2:


You can use the Object.keys() method this will return all keys in that Object as an Array. This makes it possible to do Object.keys(this.report.device).filter(key => !this.report.device[key] === null), which will return you the amount of not null keys, if this is 0 then you have your answer.

In essence relying on null properties is not such a good approach it's better to make those properties undefined or just to return a flat Object from your API.

Hope this helped.




回答3:


Approach using .some() instead of .every():

function isEmpty (obj) {
    return !Object.values(obj).some(element => element !== null);
}

This function (named isEmpty to match the name given in the question) shall return false if any obj property is not null and true otherwise.




回答4:


This is very simple and can be done with a one liner !

function IsAllPropertiesNull(obj) {
 return Object.values(obj).every(v=>v == null);
}

a = {'a': null, 'b':null};
var isAllNull = IsAllPropertiesNull(a) 
// isAllNull = true

explanation - get all values of object - iterate them and check for null

Good luck!




回答5:


Use Object.entries and Array.every

let obj = {
   property1: null,
   property2: null,
};

function isEmpty(o) {
  return Object.entries(o).every(([k,v]) => v === null);
}

if(isEmpty(obj)) {
   console.log("Object is empty");
} 


来源:https://stackoverflow.com/questions/50619910/how-to-check-if-every-properties-in-an-object-are-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!