检查数组打字稿中是否已存在新项目

时间:2017-03-13 11:45:59

标签: arrays typescript find

我是一个有属性的课程:

id: number;
motorcycleId: number;
brand: string;
model: number;
year: string;
isDeleted: boolean;

然后在我的组件中,我有一个这个模型的数组

motorcyclesList: MotorcycleModel[];

然后,我想检查一下我是否添加了一辆新摩托车,检查它是否已经存在于阵列中。

        if (this.motorcyclesList.find(x => x.model === this.motorcycle.model && 
        x.motorcycleId === this.motorcycle.motorcycleId &&
        x.year === this.motorcycle.year)) {
        //some logic if exst
    }

在这里,我总是假的。

1 个答案:

答案 0 :(得分:1)

根据@JB_Nizet和@Nitzan_Tomer的说法编辑:

确保使用this.motorcycle.motorcycleIdthis.motorcycle.model+投射到数字:

 let exist :boolean =  this.motorcyclesList.some(x => 
      x.model === +this.motorcycle.model && 
      x.motorcycleId === +this.motorcycle.motorcycleId &&
      x.year === this.motorcycle.year
 );

// do something with exist