Borislav Hadzhiev
Mon Apr 25 2022·1 min read
Photo by Josh Post
To check if an object is empty in React:
Object.keys()
method to get an array of the object's keys.length
property on the array.length
of 0
, then the object is empty.import {useEffect, useState} from 'react'; export default function App() { const [person, setPerson] = useState({}); useEffect(() => { if (Object.keys(person).length === 0) { console.log('Object is empty'); } if (Object.keys(person).length > 0) { console.log('Object is NOT empty'); } }, [person]); return ( <div> <h2>Object: {JSON.stringify(person)}</h2> <button onClick={() => setPerson({id: 1, name: 'Alice'})}> Set state </button> </div> ); }
We used the Object.keys method to get an array of all of the object's keys.
const obj = { id: 1, name: 'Alice', }; // 👇️ ['id', 'name'] console.log(Object.keys(obj)); const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ false
Object.keys
method returns an empty array if the object has no key-value pairs (if it's empty).const obj = {}; // 👇️ [] console.log(Object.keys(obj)); const isEmpty = Object.keys(obj).length === 0; console.log(isEmpty); // 👉️ true
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.
function isEmpty(obj) { for (const property in obj) { return false; } return true; } console.log(isEmpty({})); // 👉️ true console.log(isEmpty({id: 1, name: 'Alice'})); // 👉️ false
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.