{
card:[{
id:1;
details:[{id:1},{id:2}],
sheet:{
id:1
}
},{
id:2;
details:[{id:3},{id:4}],
sheet:{
id:1
}
}
]
}
{
sheet:{
id:1,
details:[{id:1},{id:2},{id:3},{id:4}]
}
}
How could I achieve this in typescript?
Went through NPM-groupBy but I don't think it really solves my problem. Is there any other way to do this?
If I understand you correctly, this would be a good use case for the array reduce method, like:
const cards = [
{
id: 1,
details: [
{id:1},
{id:2}
],
sheet:{
id:1
}
},
{
id:2,
details: [
{id:3},
{id:4}
],
sheet:{
id:1
}
},
{
id:3,
details: [
{id:5},
{id:6}
],
sheet:{
id:2
}
}
];
const sheets = cards.reduce( (sheets: Array<any>, card: any) => {
const existingSheet = sheets.find(sheet => card.sheet.id === sheet.id);
if (existingSheet) {
existingSheet.details.concat(card.details);
} else {
sheets.push({id: card.sheet.id, details: card.details});
}
return sheets;
}, []
);
console.log(sheets);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.