Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To check the empty object in react native, 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.

const emptyObject = {};

 // 👇️ Object is empty
if(Object.entries(emptyObject).length === 0){
    // 👇️ Object is empty
    console.log("Object is empty");
}

Today, I’m going to show you How do I check the empty objects in react native, as above mentioned here, I’m going to use the Object.keys() method with length to check empty objects.

Let’s start today’s tutorial how do you check the empty object in react native?

In this example, we will do

  1. Create a sample empty object state
  2. Check empty objects in a function
  3. Check empty objects in a render method and print on a screen

Let’s write code…

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

const App = () =>  {
    const [obj, setObj] = useState({});

    useEffect(() => {
        if(Object.keys(obj).length === 0){
            // 👇️ Object is empty
            console.log("Object is empty");
        } else {
          console.log("Object is not empty");
        }
    }, []);

    return (
        <View style={styles.container}>
            <Text>{Object.keys(obj).length === 0 ? "Object is empty" : "Object is not empty"}</Text>
        </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default App;

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.

Let’s check the output.

React Native, check empty object example
React Native, check empty object example

Try it yourself

I hope it’s help you, All the best 👍.