I have an array of objects:
JavaScript
x
2
1
const users: Person[] = [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}, {name: 'John', age: 14}];
2
Where
JavaScript
1
5
1
interface Person {
2
age: number;
3
name: string;
4
};
5
I need to convert it to the type NFCollection which looks so:
JavaScript
1
5
1
interface NFCollection {
2
type: string;
3
data: Person[];
4
}
5
The result should looks like this:
JavaScript
1
5
1
const nfCollection: NFCollection = {
2
type: 'adults',
3
data: [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}]
4
}
5
where the data
includes only those persons whose age >= 18.
So I could start writing something like:
JavaScript
1
2
1
const nfCollection: NFCollection = users.filter(u => u.age >= 18); // something else should follow the chain?
2
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?
JavaScript
1
5
1
const nfCollection = {
2
type: 'adults',
3
data: users.filter(u => u.age >= 18)
4
};
5
Then nfCollection
will have the same type as your NFCollection
interface.