I have an array of objects:
const users: Person[] = [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}, {name: 'John', age: 14}];
Where
interface Person { age: number; name: string; };
I need to convert it to the type NFCollection which looks so:
interface NFCollection { type: string; data: Person[]; }
The result should looks like this:
const nfCollection: NFCollection = { type: 'adults', data: [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}] }
where the data
includes only those persons whose age >= 18.
So I could start writing something like:
const nfCollection: NFCollection = users.filter(u => u.age >= 18); // something else should follow the chain?
but then I would like to convert it to the NFCollection type. How would I do that? Preferably in a memory efficient way, cos the array could be relatively big.
Advertisement
Answer
Just put the filtered array as a property of a new object?
const nfCollection = { type: 'adults', data: users.filter(u => u.age >= 18) };
Then nfCollection
will have the same type as your NFCollection
interface.