Reputation: 1015
I have an array with objects that have an object property called "operationGroup" with the "groupId" property, like this:
[{
operation: 11111,
operationGroup: null
},
{
operation: 22222,
operationGroup: {
groupId: 20
}
},
{
operation: 33333,
operationGroup: {
groupId: 1
}
},
{
operation: 44444,
operationGroup: {
groupId: 20
}
}
]
How can I find all the objects with the same groupId and add them to a new array property (groupedOperations) in each object with that groupId? It should not add the array property if the operationGroup is null or if only one groupId is found. The expected output is this:
[{
operation: 11111,
operationGroup: null
},
{
operation: 22222,
operationGroup: {
groupId: 20
},
groupedOperations: [{
operation: 22222,
operationGroup: {
groupId: 20
},
{
operation: 44444,
operationGroup: {
groupId: 20
}
}
}]
},
{
operation: 33333,
operationGroup: {
groupId: 1
}
},
{
operation: 44444,
operationGroup: {
groupId: 20
},
groupedOperations: [{
operation: 44444,
operationGroup: {
groupId: 20
}
},
{
operation: 22222,
operationGroup: {
groupId: 20
},
}
]
}
]
Upvotes: 0
Views: 51
Reputation: 194
var list = [{
operation: 11111,
operationGroup: null
},
{
operation: 22222,
operationGroup: {
groupId: 20
}
},
{
operation: 33333,
operationGroup: {
groupId: 1
}
},
{
operation: 44444,
operationGroup: {
groupId: 20
}
}
];
var groupedById = list.reduce((acc, x) => {
if(x.operationGroup != null) {
let groupId = x.operationGroup.groupId;
if(!acc[groupId]){
acc[groupId] = [];
}
acc[groupId].push(x);
}
return acc;
}, {});
list.map(x => {
if(x.operationGroup != null) {
let groupId = x.operationGroup.groupId;
if(groupedById[groupId] && groupedById[groupId].length > 1){
x["groupedOperations"] = groupedById[groupId];
}
}
});
console.log(list);
Upvotes: 1
Reputation: 974
let reqArray =[{
operation: 11111,
operationGroup: null
},
{
operation: 22222,
operationGroup: {
groupId: 20
}
},
{
operation: 33333,
operationGroup: {
groupId: 1
}
},
{
operation: 44444,
operationGroup: {
groupId: 20
}
}
]
let groups = {}
let groupReq = []
for (let req of reqArray) {
if (!req.operationGroup) continue;
if (!groups[req.operationGroup.groupId]) groups[req.operationGroup.groupId] = [];
groups[req.operationGroup.groupId].push(req)
}
for(let req of reqArray){
if(req.operationGroup && groups[req.operationGroup.groupId].length >= 2 ){
req.groupedOperations = groups[req.operationGroup.groupId]
}
groupReq.push(req)
}
console.log(groupReq,groups)
first Filter and group all operation based on groupId. then loop over request data again to update groupedOperations property
Upvotes: 1