0

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.

2
  • 1
    const myNFCollection = { type: "adults", data: nfCollection };...? Commented Nov 1, 2022 at 1:52
  • Yes, that's how I actually implemented it, but I thought I could easily do this in place, like within the same chain of functions. Commented Nov 1, 2022 at 2:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, that's how I actually implemented it, but I thought I could easily do this in place, like within the same chain of functions.
A plain object literal definition is pretty easy to do in one place..? I suppose you could chain off of the .filter to construct the surrounding object (via .reduce), but it would look really really weird and wouldn't make sense users.filter(u => u.age >= 18).reduce((_, __, ___, data) => ({ type: 'adults', data })) plus tedious initial value typing
Yes, I agree, it looks weird. I will go with the proposed solution then. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.