Typescript Array按索引查找元素

问题描述 投票:9回答:3

查找并分配具有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 }
angular typescript2.0
3个回答
20
投票

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

您可以使用filter或find方法按索引获取项目:

// ES2015

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

// ES5

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

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 ..

1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.