Home > other >  Tyepescript how to filter an array of objects depending on a specific property exists or not
Tyepescript how to filter an array of objects depending on a specific property exists or not

Time:12-24

I am try to filter objects depending on if they have a certain property.

Example:

objectArray = [{a: "", b: ""}, {a: ""}]
objectArray.filter( obj => "b" in obj ).forEach(obj => console.log(**obj.b**))

typescript complains about the obj.b, since some objects doesn't have the b property, but since I filter them out it shouldn't. What am I doing/getting wrong.

CodePudding user response:

Declare objectArray in the same statement where it is initialized (with let or const). This will allow TypeScript to infer the type of the expression objectArray.filter( obj => "b" in obj ) correctly, i.e.

const objectArray = [{a: "", b: ""}, {a: ""}];
objectArray.filter( obj => "b" in obj ).forEach(obj => console.log(obj.b)); // no error

Playground link

CodePudding user response:

Objects.keys can help you

objectArray.filter(x=> Object.keys(x).indexOf('b')>=0 );
  • Related