Finding và gán một đối tượng CategoryApi có categoryIdnguyên cảo Mảng tìm phần tử bằng cách chỉ số
export class CategoryApi {
categoryId: number;
name: string;
}
categories: CategoryApi[];
selectedCategory: CategoryApi;
selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2
tôi thấy tùy chọn javascript này nhưng nguyên cảo được phàn nàn về chức năng
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 }
Hầu hết các phương pháp đơn giản nhất sẽ là 'selectedCategory = categories.forEach (catApi => {if (catApi.id == requiredId) trả về catApi}) ' –