【问题标题】:Filtering with value inside an array of class objects使用类对象数组中的值进行过滤
【发布时间】:2021-06-14 20:44:30
【问题描述】:

我正在尝试过滤一个类对象数组,其中又嵌套了类对象。我知道这很令人困惑,我将提供一个示例代码:

//class
export class Class1{
  id:number;
  team: Teams // here  another class contains 'id' and 'name'
}
// Assume that the variable this.tmpObj contains array of Class1 objects
tmpObj:Class1[]; 

所以在这里我只想获取没有 team.id 100 的 Class1 对象。

 this.tmpObj= this.tmpObj.filter(({ team }) => {
    return team.id != 100
  })

但此代码显示 team.id 为空的错误。我尝试了其他一些过滤方式。但同样的错误。 任何想法是什么错误。提前致谢。

控制台:

【问题讨论】:

  • this.tmpObj= this.tmpObj.filter((team) => team.id !== 100) ?
  • 你应该console.log你的tmpObj看看它是否包含你期望它包含的内容。
  • @MichaelDesigaud 未过滤 team.id =100 的对象。
  • 正如我之前所说,我怀疑您的对象看起来不像您期望的那样。请在循环播放之前显示您的this.tmpObjconsole.log
  • @Random 由于上一行出现错误,它不打印

标签: angular typescript filter


【解决方案1】:

为什么在这里使用一个不需要任何特性的类? TS Interface 更适合这里。

interface Class1{
    id: number;
    team: Teams;
}

interface Teams {
    id: number;
    name: string;
}

const tmpObj: Class1[] = [ ... ];
const filtered = tmpObj.filter(({team}) => team.id !== 100);

工作示例:Playground

更新:TS 类

如果您坚持使用 TS Class 而不是接口,您可以利用 TS parameter properties 在构造函数中定义和分配成员变量。

class Class2 {
    constructor(
        private id: number,
        private team: TeamClass
    ) { }
}

class TeamClass {
    constructor(
        private id: number,
        private name: string
    ) { }
}

const tmpObj2: Class1[] = [ ... ];

const filtered2 = tmpObj.filter(({team}) => team.id !== 100);
console.log(filtered2);

工作示例:Playground

【讨论】:

  • 类和接口有什么区别?
  • @Sahal:这已被广泛记录。你可以从这里开始:stackoverflow.com/q/51716808/6513921
  • 我需要实例化对象。所以我应该只去上课。我试过你上面的代码。我遇到了同样的错误
  • 与问题中已经存在的代码有什么区别?
  • @Sahal:如果您坚持使用TS类,请使用参数属性来定义和分配成员变量。如果不是,则应手动完成。这两种方法都可以在 Playground 中使用,如果仍然出现错误,请创建一个最小的工作示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
相关资源
最近更新 更多