Typescript Array按索引查找元素

时间:2016-12-07 02:32:10

标签: angular typescript2.0

查找并分配具有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 }

3 个答案:

答案 0 :(得分:20)

JS中没有这样的方法 findByIndex ,唯一的方法是 findIndex

您可以使用过滤器查找方法按索引获取项目:

// ES2015

selectedCategory = categories.find(item => item.categoryId === 1);

// ES5

selectedCategory = categories.filter(item => item.categoryId === 1)[0];

答案 1 :(得分:2)

您可以使用find方法:

selectedCategory = categories.find(c => c.categoryApi == 2);

问题是,find函数未列在typings-file中。

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

其次,您可以编辑typings-file:

  1. 使用find更改filter并按F12(转到声明)
  2. 在typings-file中复制此行,并将该函数重命名为find,并将返回的值重命名为single-object而不是数组!
  3. 保存该文件
  4. 在您的代码中将您的filter重命名为find ..

答案 2 :(得分:0)

获取特定的参数值。 使用此代码

this.categories.find(item => item.categoryId === 1).categoryId 

categoryId可以是您想要的任何字段