无法访问数组中的对象

时间:2019-04-03 13:36:24

标签: typescript

尽管类型是Right,但是我无法将特定对象分配给变量。我有一堂课叫做Article。

export class Article {

    skuNumber: number;
    condition: string;
    eanCode: number;
    manufacturer: string;
    manufacturerIdentifier: string;
    title: string;
    description: string;
    quantity: number;
    weight: number;
    width: number;
    height: number;
    depth: number 

    constructor(
        skuNumber: number, 
        condition: string,
        eanCode: number,
        manufacturer: string,
        manufacturerIdentifier: string,
        title: string,
        description: string,
        quantity: number,
        weight: number,
        width: number,
        height: number,
        depth: number
    ) {
        this.skuNumber = skuNumber;
        this.condition = condition;
        this.eanCode = eanCode;
        this.manufacturer = manufacturer;
        this.manufacturerIdentifier = manufacturerIdentifier;
        this.title = title;
        this.description = description;
        this.quantity = quantity;
        this.weight = weight;
        this.width = width
        this.height = height;
        this.depth = depth
    }
}

在另一个文件中,我用一些示例数据填充了一个数组:

import { Article } from "./article";

export const ARTICLES: Array<Article> = [
    new Article(
        1, 
        'used', 
        5060639120949, 
        'Monster Energy', 
        'NLZ0930EG', 
        'Espresso Monster Vanilla + Espresso',
        'Ein Espressomischgetränk mit Taurin, Milch und Vanilla-Flavour.',
        12,
        0.2,
        8,
        15,
        8
    ),
    new Article(
        2, 
        'used', 
        4018931180179, 
        'G Data', 
        'NLZ0930EG', 
        'G Data Inernet Secuirty Lizenzurkunde',
        'Lizenzurkunde der Vollversion von G Data Internet Security.',
        2,
        0.2,
        8,
        15,
        0
    ),
    new Article(
        3, 
        'used', 
        4101090000638, 
        'Staatl. Fachingen', 
        'NLZ0930EG', 
        'Mineralwasser Medium',
        'Mineralwasser Medium feinperlend und erfrischend.',
        57,
        1,
        10,
        25,
        10
    )
];

现在我要通过

搜索此数组中的特定对象
let article: Article = this.articles.filter(article => article.eanCode === eanCodeOfNeededArticle);

但是我总是会遇到这些错误:类型'Article []'缺少类型'Article'的以下属性:skuNumber,condition,eanCode,制造商以及另外8个

有人可以帮助我吗?非常感谢你!

1 个答案:

答案 0 :(得分:2)

filter根据条件返回一个数组。如果只需要一个结果,则可以使用find代替filter

let article: Article = this.articles.find(article => article.eanCode === eanCodeOfNeededArticle);

array.filter: https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

array.find:https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/find