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
Release: 2024-12-01 00:31:15
Original
941 people have browsed it

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" }
];
Copy after login

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');
Copy after login

The console.log below verifies the successful retrieval:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template