Finding and assigning a CategoryApi object having categoryId
export class CategoryApi {
categoryId: number;
name: string;
}
categories: CategoryApi[];
selectedCategory: CategoryApi;
selectedCategory = categories.findByIndex(2); //looking for categoryApi by categoryId = 2
I found this javascript option but Typescript is complaining about function
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 }
TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
There is no such method findByIndex in JS, the only method is findIndex.
You can use the filter or the find method to get the item by index:
// ES2015
selectedCategory = categories.find(item => item.categoryId === 1);
// ES5
selectedCategory = categories.filter(item => item.categoryId === 1)[0];
TO get specific parameter values. Use this code
this.categories.find(item => item.categoryId === 1).categoryId
WHere categoryId can be any field you want
You can use the find method:
selectedCategory = categories.find(c => c.categoryApi == 2);
The problem is, that the find
function isn't listed in the typings-file.
First, ignore the error-message and try it!
Second, you could edit the typings-file:
find
with filter
and press F12 (go to declaration)find
and the returned value to single-object instead of an array!filter
to find
in your code..If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With