打字稿阵列通过指数

打字稿阵列通过指数

问题描述:

查找和分配具有的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 } 
+0

最简单的方法将这个'selectedCategory = categories.forEach(catApi => {if(catApi.id == requiredId)return catApi})' –

有没有这样的方法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函数不是列表在类型文件中编辑。

首先,忽略错误消息并尝试它!

其次,您可以编辑的分型文件:

  1. 变化findfilter,然后按F12(去申报)
  2. 复制这条线的分型文件和函数重命名为find和返回值为单个对象而不是数组!
  3. 保存该文件
  4. 重命名你的代码中的回filterfind ..