find object with property of value in array in javascript

To find an object with a specific property value in an array of objects in JavaScript, you can use the Array.prototype.find() method.

Here's an example that demonstrates how to find an object with a specific property value in an array:

index.tsx
// Sample array of objects
const fruits = [
  { id: 1, name: "apple" },
  { id: 2, name: "banana" },
  { id: 3, name: "orange" }
];

// Find the object with name "banana"
const foundFruit = fruits.find(fruit => fruit.name === "banana");

console.log(foundFruit);
// Output: { id: 2, name: "banana" }
300 chars
13 lines

In the above example, the fruits array contains objects with properties id and name. We use the find() method to search for the object with the name "banana". The find() method returns the first object that satisfies the provided condition, or undefined if no object is found.

You can replace the condition fruit.name === "banana" with your own condition based on the property and value you are searching for.

Note: The find() method was introduced in ECMAScript 2015 (ES6) and may not be supported in older browsers.

related categories

gistlibby LogSnag