You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何将数组高效转换为NFCollection类型对象

问题描述

我有一个Person类型的对象数组:

const users: Person[] = [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}, {name: 'John', age: 14}];

其中Person接口定义如下:

interface Person {
    age: number;
    name: string;
};

需要将该数组转换为NFCollection类型,接口定义为:

interface NFCollection {
    type: string;
    data: Person[];
}

预期结果仅保留年龄≥18的Person对象:

const nfCollection: NFCollection = {
    type: 'adults',
    data: [{name: 'Erich', age: 19}, {name: 'Johanna', age: 34}]
}

我写了初始代码,但不知道怎么完成转换,而且希望实现方式内存高效(因为数组可能很大):

const nfCollection: NFCollection = users.filter(u => u.age >= 18); // something else should follow the chain?
解决方案

基础实现

你用filter筛选符合条件用户的思路是对的,但filter返回的是数组,而NFCollection是一个包含type和data字段的对象,直接赋值会类型不匹配。只需要把筛选后的数组放到data字段中即可:

const filteredUsers = users.filter(u => u.age >= 18);
const nfCollection: NFCollection = {
    type: 'adults',
    data: filteredUsers
};

内存高效实现(推荐)

如果数组规模较大,不想额外存储中间变量filteredUsers,可以直接将filter的结果作为data的值,这样只会创建一次筛选后的数组,没有多余内存开销:

const nfCollection: NFCollection = {
    type: 'adults',
    data: users.filter(u => u.age >= 18)
};

filter本身就是内存友好的方法,它只遍历原数组一次,创建一个仅包含符合条件元素的新数组,不会修改原数组,适合大多数场景。

极致内存优化(按需使用)

如果追求极致内存效率,且后续不需要使用原users数组,可以用for循环原地过滤(会修改原数组):

let validIndex = 0;
for (const user of users) {
    if (user.age >= 18) {
        users[validIndex++] = user;
    }
}
users.length = validIndex; // 截断数组到有效元素的长度

const nfCollection: NFCollection = {
    type: 'adults',
    data: users
};

这种方式不会创建新数组,直接复用原数组的内存空间,但会破坏原数组的内容,仅在确定原数组不再使用时才推荐。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:00:58