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!