Home >Web Front-end >JS Tutorial >How to Find an Object in a JavaScript Array Based on a Property Value?

How to Find an Object in a JavaScript Array Based on a Property Value?

DDD
DDDOriginal
2024-12-01 00:31:15986browse

How to Find an Object in a JavaScript Array Based on a Property Value?

Accessing an Array Element with Matching Object Name

Problem:

You possess an array containing unnamed objects, each comprising an array of named objects. Your objective is to retrieve the object within which the "name" property equals "string 1." Here's an exemplary array:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

Finding the Array Element:

To find the desired object, utilize the find() method, specifying a callback function that checks if the object's "name" property matches "string 1":

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

The console.log below verifies the successful retrieval:

console.log(obj); // Output: { name:"string 1", value:"this", other: "that" }

The above is the detailed content of How to Find an Object in a JavaScript Array Based on a Property Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn