Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

JSON Array of Objects in Node.js

Learn how to work with JSON arrays containing multiple objects. Understand how to access object properties, loop through records, filter data, calculate values, and manage practical collections such as students, employees, and products using Node.js.

1. What Is an Array of Objects?

An array of objects is a collection that contains multiple objects. Each object can store related information using key-value pairs.

In JSON, an array is written using square brackets [ ], and each object inside it is written using curly braces { }. Commas separate the objects.

For example, a training institute may store details of multiple students. Each student has a name, course, and marks. An array of objects allows us to represent all these records together.

Example: Students JSON Data

JSON
[
    {
        "id": 1,
        "name": "Samadhan",
        "course": "Node.js",
        "marks": 85
    },
    {
        "id": 2,
        "name": "Pradnya",
        "course": "JavaScript",
        "marks": 90
    },
    {
        "id": 3,
        "name": "Rahul",
        "course": "Node.js",
        "marks": 78
    }
]

This JSON array contains three student objects. Every object stores an ID, name, course, and marks.

Definition: A JSON array of objects is a collection of JSON objects stored inside square brackets.

2. Why Do We Use Arrays of Objects?

Applications often need to process multiple related records. An array of objects keeps these records together and makes them easier to access and process.

  • Student Records: Store details of multiple students in one collection.
  • Employee Records: Represent employee IDs, names, departments, and salaries.
  • Product Lists: Store product names, prices, and availability.
  • API Responses: Process lists of records returned by an API.
  • Filtering: Find records that match specific conditions.
  • Calculations: Calculate totals, averages, or counts from the records.

3. Structure of an Array of Objects

An array contains multiple objects. Each object contains its own properties and values.

Students Array

[ object1, object2, object3 ]

↓
Object 1

id: 1
name: "Samadhan"
marks: 85

Object 2

id: 2
name: "Pradnya"
marks: 90

Object 3

id: 3
name: "Rahul"
marks: 78

4. Parse a JSON Array of Objects

JSON data is often received as text. Use JSON.parse() to convert valid JSON text into a JavaScript array containing objects.

Program

JavaScript - app.js
const jsonText = `[
    {
        "id": 1,
        "name": "Samadhan",
        "marks": 85
    },
    {
        "id": 2,
        "name": "Pradnya",
        "marks": 90
    }
]`;

const students = JSON.parse(jsonText);

console.log(students);

Output

Output
[
  { id: 1, name: 'Samadhan', marks: 85 },
  { id: 2, name: 'Pradnya', marks: 90 }
]

Explanation: The jsonText variable stores JSON text. The JSON.parse() method converts that text into a JavaScript array of objects, which is stored in students.

5. Access Objects Using Array Indexes

Array indexes start at zero. To access an object, use its index inside square brackets. Then use dot notation to access the object's properties.

Program

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 },
    { id: 3, name: "Rahul", marks: 78 }
];

console.log(students[0].name);
console.log(students[1].name);
console.log(students[2].marks);

Output

Output
Samadhan
Pradnya
78

Explanation:

  • students[0] accesses the first object.
  • students[1] accesses the second object.
  • students[2].marks accesses the marks property of the third object.

6. Display All Objects Using for...of

The for...of loop iterates over the values in an array. It is useful when we want to process each object one by one.

Program

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 },
    { id: 3, name: "Rahul", marks: 78 }
];

for (const student of students) {
    console.log(student.name, "-", student.marks);
}

Output

Output
Samadhan - 85
Pradnya - 90
Rahul - 78

Explanation: During each iteration, the variable student refers to the current object. The loop displays the name and marks of every student.

7. Display Objects Using forEach()

The forEach() method executes a callback function for each element of an array. It is another common way to process an array of objects.

Program

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 }
];

students.forEach(function (student) {
    console.log("Name:", student.name);
    console.log("Marks:", student.marks);
});

Output

Output
Name: Samadhan
Marks: 85
Name: Pradnya
Marks: 90

Explanation: The callback receives each array element. Inside the callback, we can access that object's properties.

8. Find Records Using filter()

The filter() method creates a new array containing elements that satisfy a condition. It is useful for finding students, employees, or products that match specific criteria.

Program: Students Scoring 80 or More

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 },
    { id: 3, name: "Rahul", marks: 78 }
];

const selectedStudents = students.filter(
    student => student.marks >= 80
);

console.log(selectedStudents);

Output

Output
[
  { id: 1, name: 'Samadhan', marks: 85 },
  { id: 2, name: 'Pradnya', marks: 90 }
]

Explanation: The condition student.marks >= 80 selects only students whose marks are at least 80. Rahul is not included because his marks are 78.

9. Find One Record Using find()

The find() method returns the first element that satisfies a condition. If no element matches, it returns undefined.

Program

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 },
    { id: 3, name: "Rahul", marks: 78 }
];

const student = students.find(
    item => item.id === 2
);

console.log(student);

Output

Output
{ id: 2, name: 'Pradnya', marks: 90 }

Explanation: The condition checks whether an object's ID equals 2. The first matching object is returned and stored in the student variable.

10. Processing an Array of Objects

Once JSON text has been parsed, array methods can process the resulting objects according to the application's needs.

JSON Text

Contains multiple student records.

↓
JSON.parse()

Converts JSON text into an array of objects.

↓
forEach()

Process every record.

find()

Find the first matching record.

filter()

Select all matching records.

11. Calculate the Total of Object Values

The reduce() method processes array elements and combines their values into a single result. It can be used to calculate total marks, total prices, or other totals.

Program: Total Student Marks

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 },
    { id: 3, name: "Rahul", marks: 78 }
];

const totalMarks = students.reduce(
    (total, student) => total + student.marks,
    0
);

console.log("Total Marks:", totalMarks);

Output

Output
Total Marks: 253

Explanation: The accumulator starts at 0. During each iteration, the current student's marks are added to the running total. The final result is 85 + 90 + 78 = 253.

12. Convert an Array of Objects into JSON Text

After modifying or processing an array, we can use JSON.stringify() to convert the array back into JSON-formatted text.

Program

JavaScript
const students = [
    { id: 1, name: "Samadhan", marks: 85 },
    { id: 2, name: "Pradnya", marks: 90 }
];

const jsonText = JSON.stringify(students, null, 4);

console.log(jsonText);

Output

Output
[
    {
        "id": 1,
        "name": "Samadhan",
        "marks": 85
    },
    {
        "id": 2,
        "name": "Pradnya",
        "marks": 90
    }
]

Explanation: The JSON.stringify() method converts the JavaScript array into JSON text. The third argument, 4, formats the output with indentation.

13. Complete Practical Program

In this program, we parse a JSON array of students, display all records, find students scoring at least 80, and calculate the total marks.

Complete Program

JavaScript - app.js
const jsonText = `[
    { "id": 1, "name": "Samadhan", "marks": 85 },
    { "id": 2, "name": "Pradnya", "marks": 90 },
    { "id": 3, "name": "Rahul", "marks": 78 }
]`;

const students = JSON.parse(jsonText);

console.log("All Students:");

students.forEach(student => {
    console.log(student.name, "-", student.marks);
});

const selectedStudents = students.filter(
    student => student.marks >= 80
);

console.log("\\nStudents Scoring 80 or More:");

selectedStudents.forEach(student => {
    console.log(student.name);
});

const totalMarks = students.reduce(
    (total, student) => total + student.marks,
    0
);

console.log("\\nTotal Marks:", totalMarks);

Output

Output
All Students:
Samadhan - 85
Pradnya - 90
Rahul - 78

Students Scoring 80 or More:
Samadhan
Pradnya

Total Marks: 253

Detailed Explanation:

  • JSON.parse() converts the JSON string into an array of student objects.
  • forEach() displays each student's name and marks.
  • filter() selects students whose marks are 80 or higher.
  • reduce() calculates the total marks of all students.

14. How to Run the Program

  1. Create a folder named ArrayOfObjectsExample.
  2. Create a file named app.js.
  3. Paste the complete practical program into the file.
  4. Open a terminal in the project folder.
  5. Run the program using Node.js.

Terminal Command

Terminal
node app.js

15. Common Mistakes

Mistake Correct Approach
Using curly braces around the entire array. Use square brackets for the array.
Forgetting commas between objects. Separate array elements using commas.
Using the wrong array index. Remember that the first array index is 0.
Accessing a property on a missing object. Check that the object exists before accessing its properties.
Using find() when all matching records are required. Use filter() to return all matching records.
Confusing a JavaScript array with JSON text. Use JSON.parse() to parse text and JSON.stringify() to create JSON text.

16. Practice Tasks

Task 1: Employee Records

Create an array of three employee objects. Each employee should have an ID, name, department, and salary. Display all employee names using a loop.

Task 2: Filter Products

Create an array of product objects with name and price. Use filter() to display products costing less than ₹1,000.

Task 3: Find a Student

Create an array of student objects. Use find() to locate the student with a specific ID and display the student's name and marks.

Important Points

  • An array of objects stores multiple related records.
  • JSON arrays use square brackets and JSON objects use curly braces.
  • Use JSON.parse() to convert JSON text into a JavaScript array.
  • Use indexes and property names to access object values.
  • Use for...of or forEach() to process every object.
  • Use find() for the first matching object and filter() for all matching objects.
  • Use reduce() to calculate a combined result.
  • Use JSON.stringify() to convert a JavaScript array into JSON text.

Summary

A JSON array of objects stores multiple related records inside a single array. Each object contains key-value pairs representing its data. In Node.js, JSON.parse() converts JSON text into a JavaScript array, allowing developers to access object properties using indexes and dot notation. The for...of loop and forEach() process records, find() retrieves the first matching object, filter() selects all matching records, and reduce() calculates combined values. JSON.stringify() converts the resulting JavaScript array back into JSON text. These techniques are useful for working with student, employee, product, and API records.