Skip to content
Advertisement

How to convert array of objects into custom grouped array

I am trying to convert the data object to custom format

This is my data which i want to convert

[
  { Name: 15, GroupID: 1, Id: 1 },
  { Name: 16, GroupID: 1, Id: 1 },
  { Name: 17, GroupID: 2, Id: 2 },
  { Name: 18, GroupID: 2, Id: 2 },
  { Name: 15, GroupID: 3, Id: 3 },
  { Name: 16, GroupID: 3, Id: 3 },
  { Name: 17, GroupID: 4, Id: 4 },
  { Name: 18, GroupID: 4, Id: 4 }
];

This is what i want to acheive

  { GroupID: 1 },

  { Name: 15, Id: 1 },
  { Name: 16, Id: 1 },

  { GroupID: 2 },

  { Name: 17, Id: 2 },
  { Name: 18, Id: 2 },

  { GroupID: 3 },

  { Name: 15, Id: 3 },
  { Name: 16, Id: 3 },

  { GroupID: 4 },

  { Name: 17, Id: 4 },
  { Name: 18, Id: 4 }

This is what i have tried till now

var data = [
  { Name: 15, GroupID: 1, Id: 1 },
  { Name: 16, GroupID: 1, Id: 1 },
  { Name: 17, GroupID: 2, Id: 2 },
  { Name: 18, GroupID: 2, Id: 2 },
  { Name: 15, GroupID: 3, Id: 3 },
  { Name: 16, GroupID: 3, Id: 3 },
  { Name: 17, GroupID: 4, Id: 4 },
  { Name: 18, GroupID: 4, Id: 4 }
];

var previousGroupId;
var newObject = new Object();
for (index in data) {
  var groupId = data[index].GroupID;
  if (groupId != previousGroupId) {
    var newGroup = "GroupId" + groupId;
    newObject[newGroup] = new Array();
    for (index in data) {
      if (data[index].GroupID == groupId) {
        var customObject = {
          "GroupID": groupId,
          "Name": data[index].Name,
          "Id": data[index].Id
        };
        newObject[newGroup].push(customObject);
      }
    }
  }
  previousGroupId = groupId;
}

console.log(newObject);

even i tried to refer this Javascript group objects by property

any suggestions would be helpful.

Advertisement

Answer

Assuming an array of objects as result set, you could take a hash table with arrays and take a flat array as result set.

var data = [{ Name: 15, GroupID: 1, Id: 1 }, { Name: 16, GroupID: 1, Id: 1 }, { Name: 17, GroupID: 2, Id: 2 }, { Name: 18, GroupID: 2, Id: 2 }, { Name: 15, GroupID: 3, Id: 3 }, { Name: 16, GroupID: 3, Id: 3 }, { Name: 17, GroupID: 4, Id: 4 }, { Name: 18, GroupID: 4, Id: 4 }],
    result = Object
        .values(data.reduce((r, { Name, GroupID, Id }) => {
            r[GroupID] = r[GroupID] || [{ GroupID }];
            r[GroupID].push({ Name, Id });
            return r;
        }, {}))
        .flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement