Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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' } ]
}
Updated on: 2020-09-09T14:11:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements