Home >Web Front-end >JS Tutorial >How to Find a Specific Object in a JavaScript Array of Objects?

How to Find a Specific Object in a JavaScript Array of Objects?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 20:11:14155browse

How to Find a Specific Object in a JavaScript Array of Objects?

Locate an Entity Within an Array of Objects in Javascript

When confronted with an array of anonymous objects, each containing an array of named objects, retrieving the specific object where "name" equals "string 1" can be a challenging task. An example array resembling this structure is presented:

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

Identifying the Target Object:

Utilizing the find() method, the array can be efficiently traversed to locate the desired object:

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');

console.log(obj);

In this instance, the obj variable will contain the located object:

{ name:"string 1", value:"this", other: "that" }

The above is the detailed content of How to Find a Specific Object in a JavaScript Array of Objects?. 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