Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get length of object in react js, convert the object to array using the Object.keys() method and use the array length property it will return of your number of object.

The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

In the following example, we will take the sample object, convert it into array of object keys and use array length to get the length of your object.

let obj = {id: 1, name: "infinitbility"};

console.log(Object.keys(obj).length) // 2

Today, I’m going to show you How do i find the length of the object in react js, as above mentioned here, I’m going to use the Object.keys() method, and the array length property to get length of json object.

Let’s start today’s tutorial how do you get the length of the object in react js?

In this example, we will do

  1. take an example of a object state
  2. use the Object.keys() method, and array length property
  3. print the length of the object on the page screen
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
  const [sampleObject, setSampleObject] = useState({id: 1, name: "infinitbility"});

  return (
    <div className="App">
      <h1>{`sampleObject length is ${Object.keys(sampleObject).length}`}</h1>
    </div>
  );
}

In the above react js example, we have taken the sample object state, used Object.keys() and array length, and printed it on the screen.

I hope it helps you, All the best đź‘Ť.