Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JSON group object in JavaScript
In JavaScript, grouping JSON objects means organizing data by common properties or categories. This is useful for data analysis, filtering, and creating structured reports from collections of objects.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format for transferring data between devices. JSON objects use key-value pairs where keys are strings and values can be strings, numbers, booleans, arrays, or nested objects. For example: {"name": "Alice", "age": 25}.
const jsonData = [
{ team: 'TeamA', score: 20 },
{ team: 'TeamB', score: 30 },
{ team: 'TeamA', score: 40 },
{ team: 'TeamC', score: 50 }
]
Basic JSON Object Operations
Common operations on JSON objects include:
Access values:
obj.keyorobj["key"]Modify values:
obj.key = newValueAdd properties:
obj.newKey = newValueRemove properties:
delete obj.keyConvert to string:
JSON.stringify(obj)Parse from string:
JSON.parse(jsonString)
Method 1: Grouping by Property Using reduce()
The most efficient way to group JSON objects is using the reduce() method:
const employees = [
{ name: "Alice", department: "Engineering", salary: 70000 },
{ name: "Bob", department: "Marketing", salary: 60000 },
{ name: "Charlie", department: "Engineering", salary: 75000 },
{ name: "David", department: "Marketing", salary: 65000 }
];
// Group by department
const groupedByDept = employees.reduce((groups, employee) => {
const dept = employee.department;
if (!groups[dept]) {
groups[dept] = [];
}
groups[dept].push(employee);
return groups;
}, {});
console.log(JSON.stringify(groupedByDept, null, 2));
{
"Engineering": [
{ "name": "Alice", "department": "Engineering", "salary": 70000 },
{ "name": "Charlie", "department": "Engineering", "salary": 75000 }
],
"Marketing": [
{ "name": "Bob", "department": "Marketing", "salary": 60000 },
{ "name": "David", "department": "Marketing", "salary": 65000 }
]
}
Method 2: Grouping with forEach() Loop
An alternative approach using forEach() for simpler cases:
const products = [
{ name: "Laptop", category: "Electronics", price: 1200 },
{ name: "Shirt", category: "Clothing", price: 50 },
{ name: "Phone", category: "Electronics", price: 800 },
{ name: "Jeans", category: "Clothing", price: 80 }
];
const groupedByCategory = {};
products.forEach(product => {
const category = product.category;
if (!groupedByCategory[category]) {
groupedByCategory[category] = [];
}
groupedByCategory[category].push(product);
});
console.log("Electronics:", groupedByCategory.Electronics.length, "items");
console.log("Clothing:", groupedByCategory.Clothing.length, "items");
Electronics: 2 items Clothing: 2 items
Method 3: Grouping with Aggregation
Group objects while calculating aggregate values like sum or average:
const sales = [
{ region: "North", amount: 1000, month: "Jan" },
{ region: "South", amount: 1500, month: "Jan" },
{ region: "North", amount: 1200, month: "Feb" },
{ region: "South", amount: 1800, month: "Feb" }
];
const salesSummary = sales.reduce((summary, sale) => {
const region = sale.region;
if (!summary[region]) {
summary[region] = { totalAmount: 0, count: 0 };
}
summary[region].totalAmount += sale.amount;
summary[region].count += 1;
return summary;
}, {});
// Calculate averages
for (let region in salesSummary) {
const avg = salesSummary[region].totalAmount / salesSummary[region].count;
console.log(`${region}: Total=${salesSummary[region].totalAmount}, Average=${avg}`);
}
North: Total=2200, Average=1100 South: Total=3300, Average=1650
Comparison of Methods
| Method | Best For | Performance | Readability |
|---|---|---|---|
reduce() |
Complex grouping | Excellent | Good |
forEach() |
Simple grouping | Good | Excellent |
| With aggregation | Statistics/summaries | Good | Good |
Time and Space Complexity
All grouping methods have O(n) time complexity where n is the number of objects. Space complexity is O(n) for storing grouped results. For large datasets, consider the memory usage of creating new grouped objects.
Conclusion
JSON object grouping in JavaScript is efficiently handled with reduce() for complex cases or forEach() for simpler scenarios. Choose the method based on your data structure needs and performance requirements.
