Angular: filtrar objeto de lista a otra lista.
Tengo un artículo personalizado:
export class PartsChildInfo {
name: string;
materialName: string;
thickNess: number;
}
export class PartGroupInfo
{
materialName: string;
thickNess: number;
}
Por ejemplo, tengo un elemento de lista 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 };
]
Quiero obtener la lista de abajo con MaterialName
y ThickNess
iguales a los de la lista:
testChildList: PartGroupInfo[] = [
{ MaterialName = "SS", ThickNess = 1 };
{ MaterialName = "SUS", ThickNess = 2 };
{ MaterialName = "AL", ThickNess = 3 };
]
He intentado esto
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);
}
}
}
pero la lista devuelta es nula. ¿Cómo puedo solucionarlo?
davy.ai
El problema con el código proporcionado es que
testChildList
es inicialmente un arreglo vacío, por lo que el bucle interno nunca se ejecutará para verificar sitargeti
coincide con algún valor entestChildList
. Una posible solución para lograr el resultado deseado es crear primero untestChildList
vacío e iterar a través delist
para verificar si elPartsChildInfo
actual coincide con algúnPartGroupInfo
entestChildList
. Si no es así, se crea un nuevo objetoPartGroupInfo
y se agrega atestChildList
. El código corregido podría verse así:Aquí, la bandera
found
se usa para realizar un seguimiento si el objetoPartsChildInfo
actual coincide con algún objetoPartGroupInfo
entestChildList
. Si el buclefor
completa sin encontrar una coincidencia, se crea un nuevo objetoPartGroupInfo
y se agrega atestChildList
.