[英]Find objects with same property value and add them in new array property
我有一個包含對象的數組,這些對象具有名為“operationGroup”的 object 屬性和“groupId”屬性,如下所示:
[{
operation: 11111,
operationGroup: null
},
{
operation: 22222,
operationGroup: {
groupId: 20
}
},
{
operation: 33333,
operationGroup: {
groupId: 1
}
},
{
operation: 44444,
operationGroup: {
groupId: 20
}
}
]
如何找到具有相同 groupId 的所有對象並將它們添加到每個具有該 groupId 的 object 中的新數組屬性(groupedOperations)? 如果 operationGroup 為 null 或僅找到一個 groupId,則不應添加數組屬性。 預期的 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)
首先根據groupId對所有操作進行過濾和分組。 然后再次循環請求數據以更新 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.