Hi Friends 👋,
Welcome To Infinitbility! ❤️
To check the empty object in react js, just use the Object.keys()
method it will create an array of object keys after then you can check the length and if it’s equal to 0
means the object is empty.
Like the following example, let’s take the below array of objects example here we will find an index of id 3
and delete it from the array.
1const emptyObject = {};23 // 👇️ Object is empty4if(Object.entries(emptyObject).length === 0){5 // 👇️ Object is empty6 console.log("Object is empty");7}
Today, I’m going to show you How do I check the empty objects in react js, as above mentioned here, I’m going to use the Object.keys()
method with length to check whether the object is empty or not.
Let’s start today’s tutorial how do you check the empty object in react js?
In this example, we will do
- Create a sample empty object state
- Check empty objects in a function
- Check empty objects in a render method and print on a screen
Let’s write code…
1import React, { useState, useEffect } from "react";2export default function App() {3 const [obj, setObj] = useState({});45 useEffect(() => {6 if(Object.keys(obj).length === 0){7 // 👇️ Object is empty8 console.log("Object is empty");9 } else {10 console.log("Object is not empty");11 }12 }, []);1314 return (15 <div className="App">16 <p>{Object.keys(obj).length === 0 ? "Object is empty" : "Object is not empty"}</p>17 </div>18 );19}
As mentioned above, we are taken the example of a blank object state, use the Object.keys()
to convert object keys to the array, and printed it if the object is empty.
I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.