- How to check empty object in typescript?
- Typescript check empty object
- # Check if an Object is Empty in TypeScript
- # Creating a reusable function to check if an object is empty
- # Dealing with an edge case
- # Check if an Object is Empty using a for. in loop in TypeScript
- # Check if an Object is Empty using lodash in TypeScript
- # Additional Resources
- Check If An Object Is Empty In TypeScript
- Check if an object is empty in TypeScript
- Using the Object.keys().length method
- Using the Object.values().length method
- Summary
How to check empty object in typescript?
This tutorial will help you to check objects are empty or not in typescript, here we are using the Object.keys() method to check object has value or not.
As we know, to check an empty array we are using array length to verify array is empty or not in an object there is .length property not available then we have to first create an object to array for length using Object.keys() method.
Let start today’s tutorial How to check the empty object in typescript?
The Object.keys() method creates a separate array of object keys and now we are able to check their length to verify object is empty or not.
Let create an empty object in typescript. here I’m creating a new object but you can also use the class object.
Now when we try to check their length obj.length , we will get undefined .
let create object keys to array and check the length.
Well, when we get length property. let use in if and else to check object empty or not.
let obj: object = <>; console.log(obj.length); // undefined let objLength = Object.keys(obj).length; // 0 if(objLength == 0) console.log("Empty Object"); >
Typescript check empty object
Last updated: Jan 23, 2023
Reading time · 3 min
# Check if an Object is Empty in TypeScript
To check if an object is empty in TypeScript:
- Use the Object.keys() method to get an array of the object’s keys.
- Access the length property on the array.
- If the length property is equal to 0 , the object is empty.
Copied!interface Person name?: string; age?: number; country?: string; > const person: Person = >; if (Object.keys(person).length === 0) console.log('Object is empty'); // 👉️ this runs > else console.log('Object is NOT empty'); > const isEmpty = Object.keys(person).length === 0; console.log(isEmpty); // 👉️ true
We used the Object.keys method to get an array of the object’s keys.
Copied!// 👇️ ['name', 'age'] console.log(Object.keys( name: 'Bobby Hadz', age: 30 >));
If accessing the length property on the array of keys returns anything other than 0 , then the object is not empty.
# Creating a reusable function to check if an object is empty
You can create a reusable function if have to perform the check often.
Copied!interface Person name?: string; age?: number; country?: string; > const person: Person = >; function isEmpty(obj: Recordstring, any>): boolean return Object.keys(obj).length === 0; > // 👇️ true console.log(isEmpty(person)); // 👇️ false console.log(isEmpty( name: 'bobby hadz' >));
The function takes an object and returns true if the object is empty and false otherwise.
# Dealing with an edge case
Some objects that are created using the constructor functions that would return a false positive if we only check for the length of the object’s keys.
Copied!function isEmpty(obj: Recordstring, any>): boolean return Object.keys(obj).length === 0; > console.log(isEmpty(new String())); // 👉️ true console.log(isEmpty(new Number())); // 👉️ true
Chances are you don’t use these constructor functions with the new keyword in your code and that isn’t an issue you have to worry about.
However, you could handle the edge case by checking if the object’s constructor is equal to Object .
Copied!function isEmpty(obj: Recordstring, any>): boolean return Object.keys(obj).length === 0 && obj.constructor === Object; > console.log(isEmpty(>)); // 👉️ true console.log(isEmpty( name: 'bobby hadz' >)); // 👉️ false console.log(isEmpty(new String())); // 👉️ false
We used the logical AND (&&) operator, so the isEmpty function only returns true if both conditions are met.
Here’s what calling Object.keys() on a non-empty object looks like.
Copied!const obj = a: 1, b: 2>; console.log(Object.keys(obj)); // 👉️ ['a', 'b'] const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ false
An alternative approach is to try to iterate over the properties of the object. If there is even a single iteration, then the object is not empty.
# Check if an Object is Empty using a for. in loop in TypeScript
This is a three-step process:
- Use a for. in loop to iterate over the properties of the object.
- If there is even a single iteration, the object isn’t empty.
- If there aren’t any iterations, the object is empty.
Copied!interface Person name?: string; age?: number; country?: string; > const person: Person = >; function isEmpty(obj: Recordstring, any>): boolean for (const _key in obj) return false; > return true; > console.log(isEmpty(person)); // 👉️ true console.log(isEmpty( name: 'James' >)); // 👉️ false
The isEmpty function takes an object and attempts to iterate over the properties of the passed-in object.
If there is even 1 iteration, we know that the object has at least 1 key-value pair and is not an empty object.
If there aren’t any iterations, then the object is empty.
I’d stick to the Object.keys() approach because it is more direct and intuitive.
# Check if an Object is Empty using lodash in TypeScript
Alternatively, you can use the lodash.isEmpty() method.
Open your terminal in the root directory of your project and install lodash with the following 2 commands.
Copied!npm install lodash.isempty npm install --save-dev @types/lodash.isempty
Now you can import and use the isEmpty() method from lodash .
Copied!import isEmpty from 'lodash.isempty'; console.log(isEmpty(>)); // 👉️ true console.log(isEmpty( name: 'bobby hadz' >)); // 👉️ false
The lodash.isempty method checks if the supplied value is an empty object, collection, Map or Set .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Check If An Object Is Empty In TypeScript
To check if an object is empty in TypeScript you can use the simple way is to use the Object.keys().length method. So how to do it? Let’s see the specific steps in this post.
Check if an object is empty in TypeScript
Using the Object.keys().length method
When working with TypeScript arrays, the most popular way to check the length of the array is to use the array.length method.
Return value: a number representing the length of the array.
var myArr = [1, 2, 3, 4, 5]; console.log(myArr.length);
To check if our object is empty, we will check if its length is equal to zero or not. However, we can not use the .length method directly to check the length of an object like an array. The method is that we will first use the Object.keys() method. The Object.keys() method will return a new array representing the object’s enumerable property names.
Return value: An array that contains enumerable properties of the object.
var obj = ; console.log(Object.keys(obj));
Output:
Now we can use the array.length method to check if our object is empty or not. Completed code:
type Person = < name: string, age: number, gender: string, job: string, website: string >; var obj_1 : Person = < name: 'nhk', age: 18, gender: 'male', job: 'writer', website: 'LearnShareIT.com' >; var obj_2 = < >; function checkEmpty(obj : object) < if (Object.keys(obj).length !== 0) < console.log('This object is not empty!'); >else console.log('This object is empty!'); >; checkEmpty(obj_1); checkEmpty(obj_2);
This object is not empty! This object is empty!
Using the Object.values().length method
Another approach is to use the Object.values() method. The Object.values() method works quite like the Object.keys() method. But instead of returning an array containing the keys, it will return an array with all the values of the object.
Return value: An array that contains all the values of the object.
var obj = ; console.log(Object.values(obj));
Now let’s apply it to check if an object is empty:
type Person = < name: string, age: number, gender: string, job: string, website: string >; var obj_1 : Person = < name: 'nhk', age: 18, gender: 'male', job: 'writer', website: 'LearnShareIT.com' >; var obj_2 = < >; function checkEmpty(obj : object) < if (Object.values(obj).length !== 0) < console.log('This object is not empty!'); >else console.log('This object is empty!'); >; checkEmpty(obj_1); checkEmpty(obj_2);
This object is not empty! This object is empty!
Summary
In this tutorial, we have shown you two different common methods to check if an object is empty in TypeScript. The idea is to use the Object.keys().length or Object.values().length method. Let’s try them.
Maybe you are interested:
Hello. My name is Khanh Hai Ngo. I graduated in Information Technology at VinUni. My advanced programming languages include C, C++, Python, Java, JavaScript, TypeScript, and R, which I would like to share with you. You will benefit from my content.
Name of the university: VinUni
Major: EE
Programming Languages: C, C++, Python, Java, JavaScript, TypeScript, R