Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if specific object is empty in typescript

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.

like image 580
Unfra Avatar asked Jun 02 '17 21:06

Unfra


People also ask

How do I check if a JSON object is empty in TypeScript?

return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.

How do you check whether an object is empty or not in angular?

Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty.

Is Empty object Falsy?

There are only seven values that are falsy in JavaScript, and empty objects are not one of them.


4 Answers

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

Output : 3

Source: Object.keys()

like image 199
DeepSea Avatar answered Oct 14 '22 09:10

DeepSea


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")
}
like image 26
adiga Avatar answered Oct 14 '22 09:10

adiga


You can also use lodash for checking the object

if(_.isEmpty(this.brand)){
    console.log("brand is empty")
}
like image 20
Aravind Avatar answered Oct 14 '22 08:10

Aravind


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

like image 29
V K Avatar answered Oct 14 '22 08:10

V K