繁体   English   中英

如何计算TypeScript中嵌套数组(3级)中的元素?

[英]How to count elements from nested arrays (3 level) in TypeScript?

export interface Cars {
    items: ItemsSummary[];
}

export interface ItemsSummary{
    details: DetailsSummary[];
}

export interface DetailsSummary{
    name: string;
}

我有3级嵌套数组。 我想知道Car有多少个Details ,例如: cars.flat(t=>t.items).flat(t=>t.details).length

使用reduce

let totalDetails = cars.reduce((total, car) => {
    return total += car.items.reduce((total2, item) => {
        return total2 += item.details.length;
    }, 0);
}, 0);

您可以使用reduce来总结长度:

cars.reduce((s, o) => s + o.items.reduce((ss, oo)=> ss+ oo.details.length, 0), 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM