Description
When working with objects containing arrays, it may be necessary to know the index of an object. You can apply different JavaScript methods to uniquely identify them based on their properties and then access their indices.
In this article, you will learn how to get the index of an object in an array.
Instructions
Find Index of Object with Map and indexOf() Method
The map method is used to apply a function on each item of the array, transform it and then return it inside another array. We can use this method to get specific properties of objects which we use to identify the objects themselves. Once we identify the object that we want to know the index of, we can just call the indexOf() method.
Look at the steps to perform this action:
1. Save an array in a variable. For example:
employees = [{firstName:"John", lastName:"Doe", age:38}, {firstName:"John", lastName:"Smith", age:45}];
2. Check if each object has a property with a specific value.
3. Using the Calculate a value option, use the map function to get the key/value in a separate array.
employees.map(item => item.age).indexOf(45)
4. Save the result in a new variable.
Find the Index of an Object with findIndex() Method
The findIndex() method takes a function containing a test as an argument and applies it to each element of the array without making any changes to the original array. It then returns the position of the array element or -1 if no element passes the test.
Look at the steps to perform this action:
1. Save an array in a variable. For example:
employees = [{firstName:"John", lastName:"Doe", age:38}, {firstName:"John", lastName:"Smith", age:45}];
2. Using the Calculate a value option, use the findIndex() method to get the key/value in a separate array.employees.findIndex(item => { return item.age == 45});
Here's a project you can check as an example: