Solution

To get the first element of the object in react js, create an array of keys using the Object.keys() method, get the first key of an object by passing 0 in your array of keys, then use your first key to access the first value of your object.

Snippet

In this snippet, we will create an object and use the above solution to get the first element of the object.

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

const objKeys = Object.keys(obj);
const firstKey = objKeys[0];
const firstValue = obj[firstKey];
console.log("firstValue", firstValue);

If you don’t know if the object has data or does not like it, please check the array keys length before accessing the first element of the array keys else if an array of keys is empty your code will crash.

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

const objKeys = Object.keys(obj);

if (objKeys.length > 0) {
  const firstKey = objKeys[0];
  const firstValue = obj[firstKey];
  console.log("firstValue", firstValue);
} else {
  console.log("Object is empty");
}

Example

In this example, we will show the first element of the object in the console and page in react js.

Let’s start coding…

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

  useEffect(() => {
    console.log(getFirstElement());
  }, []);

  const getFirstElement = () => {
    const objKeys = Object.keys(obj);

    if (objKeys.length > 0) {
      const firstKey = objKeys[0];
      return obj[firstKey];
    } else {
      return "Object is empty";
    }
  };

  return (
    <div className="App">
      <h1>{`Object First Element`}</h1>
      <p>{getFirstElement()}</p>
    </div>
  );
}

Output

profile

codesandbox