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

How to Find and Replace an Object in a JavaScript Array Based on a Specific Property?

Patricia Arquette
Release: 2024-11-28 14:26:12
Original
259 people have browsed it

How to Find and Replace an Object in a JavaScript Array Based on a Specific Property?

Finding an Object with a Specific Property in an Array of Objects

In Javascript, an array of unnamed objects can be searched for a particular object based on a property-value match. Consider the following array:

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

Finding the Object:

To find the object with the property "name" set to "string 1", use the find() method. The syntax is:

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

This code iterates through the array and returns the first object where the condition o.name === 'string 1' is true. The resulting obj would contain the following data:

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

Replacing the Found Object:

Once the object is found, it can be replaced with an edited version. To do this, use the findIndex() method to get the index of the object within the array:

let index = array.findIndex(o => o.name === 'string 1');
Copy after login

Then, use the array's splice() method to replace the object at that index:

array.splice(index, 1, { new_name: "string 1", new_value: "updated" });
Copy after login

Now, the array will contain the updated object:

[
    { name:"string 1", value:"updated", other: "that" },
    { name:"string 2", value:"this", other: "that" }
]
Copy after login

The above is the detailed content of How to Find and Replace an Object in a JavaScript Array Based on a Specific Property?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template