我有一個物件陣列:
const users: Person[] = [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}, {name: 'John', age: 14}];
在哪里
interface Person {
age: number;
name: string;
};
我需要將其轉換為 NFCollection 型別,如下所示:
interface NFCollection {
type: string;
data: Person[];
}
結果應如下所示:
const nfCollection: NFCollection = {
type: 'adults',
data: [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}]
}
其中data
僅包括年齡 >= 18 的人。
所以我可以開始寫類似的東西:
const nfCollection: NFCollection = users.filter(u => u.age >= 18); // something else should follow the chain?
但后來我想將其轉換為 NFCollection 型別。我該怎么做?最好以記憶體有效的方式,因為陣列可能相對較大。
uj5u.com熱心網友回復:
只是將過濾后的陣列作為新物件的屬性?
const nfCollection = {
type: 'adults',
data: users.filter(u => u.age >= 18)
};
然后將具有與您的界面nfCollection
相同的型別。NFCollection
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524778.html
上一篇:用一個回圈展平物件陣列