查找并分配具有categoryId的CategoryApi对象
export class CategoryApi {
categoryId: number;
name: string;
}
categories: CategoryApi[];
selectedCategory: CategoryApi;
selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2
我发现这个javascript选项但是Typescript抱怨功能
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
在JS中没有这样的方法findByIndex,唯一的方法是findIndex。
您可以使用filter或find方法按索引获取项目:
// ES2015
selectedCategory = categories.find(item => item.categoryId === 1);
// ES5
selectedCategory = categories.filter(item => item.categoryId === 1)[0];
您可以使用find方法:
selectedCategory = categories.find(c => c.categoryApi == 2);
问题是,find
函数未列在typings-file中。
首先,忽略错误消息并试一试!
其次,你可以编辑typings-file:
find
更改filter
并按F12(转到声明)find
,并将返回的值重命名为single-object而不是数组!filter
重命名为find
..获取特定参数值。使用此代码
this.categories.find(item => item.categoryId === 1).categoryId
categoryId可以是您想要的任何字段