Check if specific object is empty in typescript

Solution 1:

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

Output : 3

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Solution 2:

You can use Object.keys like this:

class Brand { }
const brand = new Brand();

if (Object.keys(brand).length === 0) {
  console.log("No properties")
}

If you want to check if the object has at least one non-null, non-undefined property:

  • Get all the values of the object in an array using Object.values()
  • Check if at least one of has value using some

const hasValues = 
    (obj) => Object.values(obj).some(v => v !== null && typeof v !== "undefined")

class Brand { }
const brand = new Brand();

if (hasValues(brand)) {
  console.log("This won't be logged")
}

brand.name = null;

if (hasValues(brand)) {
  console.log("Still no")
}

brand.name = "Nike";

if (hasValues(brand)) {
  console.log("This object has some non-null, non-undefined properties")
}

Solution 3:

You can also use lodash for checking the object

if(_.isEmpty(this.brand)){
    console.log("brand is empty")
}