Typescript Index Search Array Element

Search and assign CategoryApi object with 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 parameter, but Typescript complains about the 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 } 
+11
source share
3 answers

There is no such findByIndex method in JS , the only method is findIndex .

You can use the filter or 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]; 
+21
source

You can use the find method:

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

The problem is that the find function is not specified in the typings file.

First, ignore the error message and try!

Secondly, you can edit the typings file:

  • change find to filter and press F12 (go to declaration)
  • copy this line to the file-typing and rename the function to find and the return value into one object instead of an array!
  • save this file
  • rename filter back to find in your code.
+2
source

To get specific parameter values. Use this code

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

Where CategoryId can be any field you want

+2
source

Source: https://habr.com/ru/post/1260908/


All Articles