我有一個自定義專案:
export class PartsChildInfo {
name: string;
materialName: string;
thickNess: number;
}
export class PartGroupInfo
{
materialName: string;
thickNess: number;
}
例如,我有一個串列項 PartsChildInfo:
list : PartsChildInfo = [
{ Name = "GA8-0608" , MaterialName = "SS" , ThickNess = 1 };
{ Name = "05F1-051" , MaterialName = "SUS" , ThickNess = 2 };
{ Name = "2B73-002" , MaterialName = "AL" , ThickNess = 3 };
{ Name = "01-20155" , MaterialName = "SS" , ThickNess = 1 };
{ Name = "02MEG099" , MaterialName = "SUS" , ThickNess = 2 }; ]
我想從串列中獲取與 MaterialName、ThickNess 相同的串列:
testChildList : PartGroupInfo = [
{ MaterialName = "SS" , ThickNess = 1 };
{ MaterialName = "SUS" , ThickNess = 2 };
{ MaterialName = "AL" , ThickNess = 3 }; ]
我正在使用 Typescript Angular
我試過這個
testChildList : PartGroupInfo[] = [];
for (let i = 0; i < list.length; i ) {
let targeti = list[i];
for (let j = 0; j < this.testChildList.length; j ) {
let targetj = this.testChildList[j];
if (targeti.materialName != targetj.materialName && targeti.thickNess != targetj.thickNess) {
let item = new PartGroupInfo();
item.materialName = targeti.materialName;
item.thickNess = targeti.thickNess;
this.testChildList.push(item);
}
}
}
但回傳串列為空。我該如何解決?
uj5u.com熱心網友回復:
也許用于.forEach迭代list陣列,檢查專案是否存在于testChildListvia index。當索引為 -1(不存在)時推item送到testChildList。
this.list.forEach((item) => {
var i = this.testChildList.findIndex(
(x) =>
x.materialName == item.materialName && x.thickNess == item.thickNess
);
if (i == -1)
this.testChildList.push({
materialName: item.materialName,
thickNess: item.thickNess,
});
});
StackBlitz 上的示例解決方案
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/369879.html
