Solution

To get length of object in react js, first convert it into in array then use array.length property it will count and return number of elements have in object.

To convert object to array we will use Object.keys() method which will create array of keys have in object.

Object.keys()

The Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object.

array.length

The length property of an Array object represents the number of elements in that array.

The value of the length property is a non-negative integer with a value less than 232.

Snippet

In this snippet, we will create an object and convert it into array and use the array.length property to show the length of object.

const obj = {
  id: 1,
  name: "John",
  work: "none of your business",
};

const keys = Object.keys(obj);
let length = keys.length;

console.log(length); // 3

Example

In this example, we will show the length of object in the console and page.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [obj, setObj] = useState({
    id: 1,
    name: "John",
    work: "none of your business",
  });

  useEffect(() => {
    console.log("Length Of Object", getLengthOfObject());
  }, []);

  const getLengthOfObject = () => {
    const keys = Object.keys(obj);
    return keys.length;
  };

  return (
    <div className="App">
      <h1>{`Length Of Object`}</h1>
      <p>{getLengthOfObject()}</p>
    </div>
  );
}

Output

Object, Length

codesandbox