I want to check a javascript object to see if any of it's properties are missing without checking each property individually.
I can use "hasownproperty" or do if/else statements to check if each one is null/undefined, I wanted a shorter way of checking an object.
Use Array::some()
on object values (get them with Object.values()
) (this will return true
if ANY property's value is null
or undefined
):
const obj = { a: null, b: 'there', c: 0, d: undefined };
console.log("Missing?", Object.values(obj).some(v => v === undefined || v === null));
If you want it the fastest possible, write your own function:
const obj = { a: null, b: 'there', c: 0, d: undefined };
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
console.log("Missing?", hasNullProperties(obj));
And a benchmark:
<script benchmark data-count="10000000">
const obj = { a: null, b: 'there', c: 0, d: undefined };
// @benchmark Array::some()
Object.values(obj).some(v => v === undefined || v === null);
// @benchmark custom func
function hasNullProperties(obj){
for(const k in obj){
if(obj[k] === undefined || obj[k] === null){
return true;
}
}
return false;
}
// @run
hasNullProperties(obj);
</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>