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
[
{
"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.
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
const jsonText = `[
{
"id": 1,
"name": "Samadhan",
"marks": 85
},
{
"id": 2,
"name": "Pradnya",
"marks": 90
}
]`;
const students = JSON.parse(jsonText);
console.log(students);
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
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
Samadhan
Pradnya
78
Explanation:
-
students[0]accesses the first object. -
students[1]accesses the second object. -
students[2].marksaccesses 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
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
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
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
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
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
[
{ 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
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
{ 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
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
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
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
[
{
"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
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
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
-
Create a folder named
ArrayOfObjectsExample. -
Create a file named
app.js. - Paste the complete practical program into the file.
- Open a terminal in the project folder.
- Run the program using Node.js.
Terminal Command
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...oforforEach()to process every object. -
Use
find()for the first matching object andfilter()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.