我正在使用打字稿。
我想使用 userData 和 GroupData 陣列創建一個新陣列。
如果 userData 陣列中的 groupId 和 GroupData 陣列中的 userGroupId 相同,我想把第一個型別為 1 的物件的組放在背景關系中。
如果沒有type1,我想輸入null。
我想創建一個像①這樣的陣列。
使用推送的地方會發生錯誤。(“UserGroup”型別的屬性“push”不存在。ts(2339))
①Wanted Value
[
{ id: 1, groupId: 10, title: 'test1', content: 'aa' },
{ id: 2, groupId: 11, title: 'test2', content: 'bb' },
{ id: 3, groupId: 12, title: 'test3', content: 'null' },
{ id: 4, groupId: 13, title: 'test4', content: 'dd' },
];
const userData = [
{ id: 1, groupId: 10, title: 'test1' },
{ id: 2, groupId: 11, title: 'test2' },
{ id: 3, groupId: 12, title: 'test3' },
{ id: 4, groupId: 13, title: 'test4' },
];
const GroupData = [
{ id: 1, userGroupId: 10, group: 'aa' type: 1},
{ id: 2, userGroupId: 11, group: 'bb',type: 1},
{ id: 3, userGroupId: 11, group: 'cc', type: 1},
{ id: 3, userGroupId: 12, group: 'cc', type: 2},
{ id: 4, userGroupId: 13, group: 'dd', type: 1},
];
type UserType = {
id: number;
groupId: number;
title: string;
};
type GroupType = {
id: number;
userId: number;
group: string;
};
type UserGroup = UserType & {
content: string;
};
const toBlock = () => {
const blocks: UserGroup[] = [];
let count = 0;
userData.map(user => {
GroupData.map(group => {
if (user.groupId === group.userGroupId) {
blocks[count].push({ ...user, content: group.group });
}
});
count ;
});
};
uj5u.com熱心網友回復:
這不是一個相當簡單的嵌套回圈場景。像這樣的東西
userData.forEach(x=>{
let firstElem = GroupData.find(g=>g.userGroupId === x.groupId && g.type === 1);
let content=null;
if(firstElem)
{
content = firstElem.group;
}
resultArr.push({id: x.id, groupId: x.groupId, title: x.title, content: content});
});
所以基本上我們正在遍歷 userData 陣列,并為它的每個專案,在 GroupData 陣列上呼叫 find (find 回傳第一個匹配項)。如果未找到匹配項,則 content 元素將為 null,否則它將具有陣列中 group 欄位的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442528.html
標籤:打字稿
上一篇:如何將innerHTML傳遞給onClick函式(Typescript)
下一篇:嵌套類的區域型別定義
