Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to group JSON data in JavaScript?
To group JSON data, you need to extract all the keys and use the push(). Following is the code −
Example
var details=
{
"1":
{
name:"John"
},
"2":
{
name:"John"
},
"3":
{
name:"David"
}
var objectWithGroupByName = {};
for (var key in details){
var name = details[key].name;
if (!objectWithGroupByName[name]){
objectWithGroupByName[name] = [];
}
objectWithGroupByName[name].push(details[key]);
}
console.log(objectWithGroupByName);
To run the above program, you need to use the following command −
node fileName.js.
Output
Here, my file name is demo122.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo122.js
{
John: [ { name: 'John' }, { name: 'John' } ],
David: [ { name: 'David' } ]
}Advertisements