Hi 👋,

Welcome To Infinitbility! ❤️

Today, we will learn to get specific data from JSON with example using objects, and an array of objects.

So, we are Going to learn to get specific data from 👇

Table of content

  1. React object example
  2. React array of the object example

React object example

To access any property of an object, we have to write the key of an object property.

As we know to create an object we need key and value pairs.

Let’s create sample object data and access any specific data like object.id. or object.name.

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [sampleObject, setSampleObject] = useState({});

  useEffect(() => {
    let sampleObject = {
      id: 1,
      name: "infinitbility"
    };
    setSampleObject(sampleObject);
  }, []);

  return (
    <div className="App">
      <h1>Hello {sampleObject.name}</h1>
      <h2>Coding feels like fuel for my life!</h2>
    </div>
  );
}

Here, we just create state and store when component mount, and in render, we access object data from the key.

Output

React, object, access, specific, object
React, Access specific data from object example

React array of object example

In this section, we will use a sample array and find a specific object from the array and store it in state and use it like above 👆.

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [sampleObject, setSampleObject] = useState({});

  useEffect(() => {
    let sampleArray = [
      {
        id: 1,
        name: "infinitbility",
        domain: "infinitbility.com"
      },
      {
        id: 2,
        name: "aGuideHub",
        domain: "aguidehub.com"
      }
    ];
    let sampleObject = sampleArray.find(e => e.id == 2);
    setSampleObject(sampleObject);
  }, []);

  return (
    <div className="App">
      <h1>Hello {sampleObject.name}</h1>
      <h2>Coding feels like fuel for my life!</h2>
    </div>
  );
}

Here, find id 2 in array to specific data related aGuideHub and storing in the state.

React, array of object, access, specific, object
React, Access specific data from array of object example

Thanks for reading…