How To Check If Every Properties In An Object Are Null
Solution 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()
Solution 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.
Solution 3:
Approach using .some() instead of .every():
functionisEmpty (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.
Solution 4:
This is very simple and can be done with a one liner !
functionIsAllPropertiesNull(obj) {
returnObject.values(obj).every(v=>v == null);
}
a = {'a': null, 'b':null};
var isAllNull = IsAllPropertiesNull(a)
// isAllNull = trueexplanation - get all values of object - iterate them and check for null
Good luck!
Solution 5:
Use Object.entries and Array.every
let obj = {
property1: null,
property2: null,
};
functionisEmpty(o) {
returnObject.entries(o).every(([k,v]) => v === null);
}
if(isEmpty(obj)) {
console.log("Object is empty");
}
Post a Comment for "How To Check If Every Properties In An Object Are Null"