map & JSON

JSON & Map() in react.js

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and sharing data. JSON looks like JavaScript objects, but it is purely a text format.

Why is JSON useful?
  1. It is easy for humans to read and write.
  2. It is easy for machines to parse and generate.
  3. It is widely used in web development to transfer data between servers and web applications.
Example of JSON:
{
"name": "Aravind",
"age": 30,
"email": "aravind@rephel.com",
"skills": ["JavaScript", "React", "Node.js"]
}
Key Rules of JSON:
  1. Data is in key-value pairs.
    • "key": "value"
  2. Strings must be wrapped in double quotes (").
  3. JSON supports basic data types:
    • Strings: "Hello"
    • Numbers: 123
    • Booleans: true or false
    • Arrays: [1, 2, 3]
    • Objects: { "key": "value" }
    • Null: null

What is the map() Function?

The map() function is a built-in array method in JavaScript. It is used to create a new array by applying a given function to each element in an existing array.

Think of map() as a factory line. You give it a set of raw materials (an array), and it processes each item (element in the array) according to your instructions (the function) and returns a new set of products (a new array).

Example:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]
  • Input: [1, 2, 3, 4]
  • Operation: Multiply each number by 2.
  • Output: [2, 4, 6, 8]

How are map() and JSON Used Together in Vanilla JS ?

When you have an array of JSON objects, you can use map() to process and display the data.

Example:

const users = [
{ id: 1, name: "Aravind" },
{ id: 2, name: "Priyadharshini" }
];

const userNames = users.map((user) => user.name);
console.log(userNames); // Output: ["Aravind", "Priyadharshini"]

Here:

  1. users is an array of JSON objects.
  2. map() extracts the name property from each object and creates a new array with just the names.

JSON & Map() in React.json

If you want use fetch() or the import method to load JSON data in React, you can directly import the JSON file as a module. This method is simpler for static JSON files and doesn’t require a fetch request.

Step 1: Create sample.json

Place the JSON file in the src folder or a subfolder, for example: src/data/sample.json.

[
{
"id": 1,
"name": "Aravind",
"email": "aravind@rephel.com",
"role": "Developer"
},
{
"id": 2,
"name": "Priyadharshini",
"email": "Priyadharshini@rephel.com",
"role": "Designer"
},
{
"id": 3,
"name": "Ashwini",
"email": "ashwini@rephel.com",
"role": "Project Manager"
}
]

Step 2: Import and Display JSON Data in React

App.js

import React from "react";
import userData from "./data/sample.json"; // Import the JSON file

function App() {
return (
<div>
<h1>User List</h1>
{/* Use the map function to iterate over the JSON data */}
<ul>
{userData.map((user) => (
<li key={user.id}>
<h3>{user.name}</h3>
<p>Email: {user.email}</p>
<p>Role: {user.role}</p>
</li>
))}
</ul>
</div>
);
}

export default App;

Explanation

  1. Importing JSON File
    • import userData from "./data/sample.json";:
      • This directly imports the JSON file as a JavaScript object.
      • The userData variable contains the parsed JSON array.
  2. Using map() Function
    • userData.map((user) => ...: Iterates over the array of user objects.
    • Each user object is destructured and its properties are used to display content.
  3. Rendering Data
    • The map() function dynamically generates list items for each user, displaying their name, email, and role.
  4. key Prop
    • The key attribute ensures efficient rendering and helps React identify list items uniquely.

Directory Structure

project/
├── src/
│ ├── data/
│ │ ├── sample.json
│ ├── App.js
├── package.json

Output

User List

  1. Aravind
  2. Priyadharshini
  3. Ashwini

Pros of Importing JSON

  • Simple and efficient for small or static JSON files.
  • No need for a fetch request or async/await.

When to Use fetch Instead?

  • If the JSON file is hosted on a server or needs to be fetched dynamically.
  • If you plan to work with APIs or need live updates.

Leave a Reply

Your email address will not be published. Required fields are marked *