Home >Web Front-end >JS Tutorial >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" } ];
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');
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" }
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');
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" });
Now, the array will contain the updated object:
[ { name:"string 1", value:"updated", other: "that" }, { name:"string 2", value:"this", other: "that" } ]
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!