Skip to content
the poor coder

how to locate an object with a spcific key in js array

Poor Man
Published
Reading time
1 min read

How to Locate an Object with a Specific Key in JS Array#

If you have an array of objects in JavaScript and you want to find the index of the object that has a specific key, you can do so using the Array.prototype.findIndex() method.

Let's say you have an array of objects that represent books:

JavaScript
const books = [
  { id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
  { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
  { id: 3, title: '1984', author: 'George Orwell' }
]

If you want to find the index of the book with an id of 2, you can use the following code:

JavaScript
const index = books.findIndex(book => book.id === 2)
console.log(index) // Output: 1

The Array.prototype.findIndex() method takes a function as its argument. This function is called for each element in the array until it finds an element that satisfies the condition specified in the function. In this case, we are checking if the id of the book is equal to 2.

If the function returns true, the Array.prototype.findIndex() method returns the index of that element. If the function returns false for every element in the array, it returns -1.

You can also use the Array.prototype.find() method to find the actual object instead of its index:

JavaScript
const book = books.find(book => book.id === 2)
console.log(book) // Output: { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }

The Array.prototype.find() method works in a similar way to the Array.prototype.findIndex() method, but it returns the element itself instead of its index.

So, these are the two ways you can locate an object with a specific key in a JavaScript array.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC