Check if specific object is empty in typescript

Viewed 152918

How to check if an object is empty?

ex:

private brand: Brand = new Brand();

I tried:

if (this.brand) {
  console.log('is empty');   
}

not working.

12 Answers

Use Object.keys(obj).length to check if it is empty.

Output : 3

Source: Object.keys()

Object.keys(myObject).length == 0

A Map obj can be created with empty properties and size might not work . Object might not be equal to empty or undefined

But with above code you can find whether an object is really empty or not

let contacts = {};
if(Object.keys(contacts).length==0){
      console.log("contacts is an Empty Object");
}else{
      console.log("contacts is Not an Empty Object");
}

Here is a comparison between the 2 most popular answers, they do have slightly different implications:

let o1 = {}
console.log(JSON.stringify(o1) === '{}')
console.log(Object.keys(o1).length === 0)
// true
// true

let o2 = { p: undefined }
console.log(JSON.stringify(o2) === '{}')
console.log(Object.keys(o2).length === 0)
// true
// false

let o3 = { l: null }
console.log(JSON.stringify(o3) === '{}')
console.log(Object.keys(o3).length === 0)
// false
// false

This is the fastest construct that I'm aware of, albeit it uses somewhat puzzling for...in loop that doesn't loop (in my tests it's about 2x faster than Object.keys)

export function isObjectEmpty(object: Record<string, unknown>): boolean {
  for (const property in object) {
    // if any enumerable property is found object is not empty
    return false;
  }

  return true;
}
JSON.stringify(this.brand) === '{}'

Careful about Object.keys and Array.some solutions, in case if your object is not even initialized and worth null.

Also care that there is no key worthing undefined.

const objNotInitialized = null;

console.log(Object.keys(objNotInitialized));


You could add an extra check in that case, leading to the final soluce :

function isEmpty(obj) {
  return !obj || !Object.keys(obj).some(x => obj[x] !== void 0);
}

console.log(isEmpty({
  x: void 0,
}));

console.log(isEmpty(null));

console.log(isEmpty({
  key: 'value',
}));


If you can use Object.values :

function isEmpty(obj) {
  return !obj || !Object.values(obj).some(x => x !== void 0);
}

console.log(isEmpty({
  x: void 0,
}));

console.log(isEmpty(null));

console.log(isEmpty({
  key: 'value',
}));


const obj = {};

// Using Object.keys to loop on the object keys and count them up
if (!Object.keys(obj).length) {
  console.log('#1 obj is empty');
}

// What if a key worth undefined ?
const objWithUndefinedKey = {
  x: void 0,
};

// Using Object.keys is not enough, we have to check the value behind to remove
// undefined values
if (!Object.keys(objWithUndefinedKey).some(x => objWithUndefinedKey[x] !== void 0)) {
  console.log('#2 obj is empty');
}

// Or more elegant using Object.values
if (!Object.values(objWithUndefinedKey).some(x => x !== void 0)) {
  console.log('#3 obj is empty');
}

// Alternative is to use for ... in
let empty = true;

for (key in objWithUndefinedKey) {
  if (objWithUndefinedKey[key] !== void 0) {
    empty = false;
  }
}

if (empty) {
  console.log('#4 obj is empty');
}

Object.values(this.brand).some(b => b != null);

The good approach is to have a short function that you can use everywhere in your app :

export const isEmpty = (obj) => {
return obj === null || undefined
    ? true
    : (() => {
            for (const prop in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                    return false;
                }
            }
            return true;
        })();
};

If you build ECMA 7+ can try Object.entries(obj).length === 0 && obj.constructor === Object

Related