0

I'm trying to filter an array of class objects which have again class objects nested in it. I know it is confusing, I'll provide a sample code:

//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[]; 

So here I want to take only the Class1 objects not having team.id 100.

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

But this code shows error that team.id is null.I tried some other ways of filtering. But same error. Any idea what was the error. Thanks in advance.

Console: console.log

Sahal
  • 105
  • 13

1 Answers1

0

Why use a class here where none of it's features are required? TS Interface would be better fit here.

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

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

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

Working example: Playground

Update: TS Class

If you insist on using TS Class instead of interfaces, you could leverage TS parameter properties to define and assign member variables in the constructor.

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

Working example: Playground

ruth
  • 29,535
  • 4
  • 30
  • 57
  • whats the difference b/w both class and interface? – Sahal Mar 17 '21 at 13:53
  • @Sahal: This has already been documented extensively. You could start here: https://stackoverflow.com/q/51716808/6513921 – ruth Mar 17 '21 at 13:55
  • I need to instantiate object. So I should go for class only. And i tried your above code. Same error I'm getting – Sahal Mar 17 '21 at 13:58
  • What is the difference with the code which is already in the question ? – Random Mar 17 '21 at 13:58
  • @Sahal: If you insist on using TS class, use parameter properties to define and assign the member variables. If not it should be done manually. Both the methods work in the playground, if you still get an error create a minimal working example. – ruth Mar 17 '21 at 14:08
  • @Random: The variable doesn't seem to initialized in the question. Interfaces doesn't bother with it. – ruth Mar 17 '21 at 14:08
  • Actually springboot returns the values and it is stored in that variable. – Sahal Mar 17 '21 at 14:10
  • @Sahal: Then you need to show how the values are retrieved, if the values indeed are of the same structure that you've shown and how is the type assigned to the response. – ruth Mar 17 '21 at 15:47