5
查找和分配具有的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 }
最簡單的方法將這個'selectedCategory = categories.forEach(catApi => {if(catApi.id == requiredId)return catApi})' –