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' } ]
}