Solution

To get the last element of the object in react js, create an array of keys using the Object.keys() method, and get the last key of an object by passing objKeys.length - 1 in your array of keys, then use your last key to access the last value of your object.

Snippet

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

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

const objKeys = Object.keys(obj);
const lastKey = objKeys[objKeys.length - 1];
const lastValue = obj[lastKey];
console.log("lastValue", lastValue);

If you don’t know the object has data or does not like it, please check the array keys length before accessing the last 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 lastKey = objKeys[objKeys.length - 1];
  const lastValue = obj[lastKey];
  console.log("lastValue", lastValue);
} else {
  console.log("Object is empty");
}

Example

In this example, we will show the last 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(getLastElement());
  }, []);

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

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

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

Output

profile

codesandbox