[英]Find objects with same property value and add them in new array property
I have an array with objects that have an object property called "operationGroup" with the "groupId" property, like this:我有一个包含对象的数组,这些对象具有名为“operationGroup”的 object 属性和“groupId”属性,如下所示:
[{
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?如何找到具有相同 groupId 的所有对象并将它们添加到每个具有该 groupId 的 object 中的新数组属性(groupedOperations)? It should not add the array property if the operationGroup is null or if only one groupId is found.如果 operationGroup 为 null 或仅找到一个 groupId,则不应添加数组属性。 The expected output is this:预期的 output 是这样的:
[{
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
},
}
]
}
]
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.首先根据groupId对所有操作进行过滤和分组。 then loop over request data again to update groupedOperations property然后再次循环请求数据以更新 groupedOperations 属性
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.