【问题标题】:Filter list object to other list in Angular将列表对象过滤到Angular中的其他列表
【发布时间】:2022-01-06 19:24:19
【问题描述】:

我有一个自定义项目:

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);
       }
    }
 }

但返回列表为空。我该如何解决?

【问题讨论】:

  • 什么是data[j]
  • @YongShun 我是 sr,我在帖子中编辑但仍然返回空列表
  • 我猜this.testChildList.push(item);应该是testChildList.push(item);
  • @N.F.谢谢,但它仍然返回空列表
  • 你要返回哪个变量?

标签: angular typescript list listobject


【解决方案1】:

也许使用.forEach 来迭代list 数组,通过index 检查该项目是否存在于testChildList 中。当索引为-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,
    });
});

Sample Solution on StackBlitz

【讨论】:

  • 第一个“testChildList”是空列表。我想过滤“列表”以获取同时具有 materialName 和 ThickNess 的元素。你能帮我看一下吗?
  • 好吧,我总结一下你的需求,你想从list 获取materialName和thickNess,并且是不同的?
  • 是的,没错
  • 嗨,感谢您澄清要求,我已经更新了我的答案。
  • 我跟着它工作了。非常感谢您。我会把它作为答案!
猜你喜欢
  • 2021-09-26
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2022-01-16
  • 2015-03-24
相关资源
最近更新 更多