AppDividend
Latest Code Tutorials

Javascript: Find Object in Array

0

You often get in the scenarios where you have an array of objects, and you need to find some specific object inside this array based on some property of the object. Let’s see how to find an object in the array in JavaScript.

Javascript: Find Object in Array

To find Object in Array in JavaScript, use array.find() method. Javascript array find() function returns the value of the first item in the provided array that satisfies the provided testing function.

The find() function returns the value of the first item in an array that pass the test (provided as a function). JavaScript find() method executes the function once for each item present in the array:

  1. If it finds the array item where the function returns a true value, find() returns the value of that array item (and does not check the remaining values)
  2. Otherwise, it returns undefined.

Syntax

array.find(function(currentValue, index, arr),thisValue)

Parameters

function(currentValue, index, arr)

The function parameter required. A function to be run for each item in the array.

Function arguments:

currentValue: It is a required parameter. The value of the current element.

index: It is optional. The array index of the current element.

arr: It is optional. The array object the current element belongs to.

thisValue: Optional. A value to be passed to the item to be used as its “this” value. If this parameter is empty, the value “undefined” will be passed as its “this” value.

Return Value

The value of the first item in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Example

Let’s find an object in an array by one of its properties.

// app.js

const inventory = [
  { name: 'table', quantity: 1 },
  { name: 'sofa', quantity: 2 },
  { name: 'chair', quantity: 3 }
];

function isTable(inv) {
  return inv.name === 'chair';
}

console.log(inventory.find(isTable));

Output

{ name: 'chair', quantity: 3 }

In this example, we are finding the object based on its name property. It returns the chair object if the chair object exists in the array. Otherwise, it will return undefined.

Using ES6 to find an object in the array

We will use an arrow function which shorter our code, and it is more readable.

// app.js

let inventory = [
  { name: 'table', quantity: 1 },
  { name: 'sofa', quantity: 2 },
  { name: 'chair', quantity: 3 }
];

console.log(inventory.find(obj => obj.name == 'table'));

Output

{ name: 'table', quantity: 1 }

You will get the same result, but using this syntax, you have to look out for browser compatibility issues.

That is it for Javascript find an object in the array example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.