打字稿阵列通过指数
问题描述:
查找和分配具有的categoryId打字稿阵列通过指数
export class CategoryApi {
categoryId: number;
name: string;
}
categories: CategoryApi[];
selectedCategory: CategoryApi;
selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2
一个CategoryApi对象找到元素,我发现这个JavaScript选项,但打字稿抱怨功能
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 }
答
有没有这样的方法findByIndex在JS,唯一的方法是findIndex。
可以使用过滤或找到方法,通过指数来获得的项目:
// 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
函数不是列表在类型文件中编辑。
首先,忽略错误消息并尝试它!
其次,您可以编辑的分型文件:
- 变化
find
与filter
,然后按F12(去申报) - 复制这条线的分型文件和函数重命名为
find
和返回值为单个对象而不是数组! - 保存该文件
- 重命名你的代码中的回
filter
到find
..
最简单的方法将这个'selectedCategory = categories.forEach(catApi => {if(catApi.id == requiredId)return catApi})' –