Finding Values in Arrays of Objects with JavaScript
Similar to previous queries, this inquiry presents a distinct scenario. We have an array of unnamed objects that contain arrays of named objects. The requirement is to locate the object with the "name" property set to "string 1." For reference, consider the following array:
var array = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ];
Modifying the Found Object:
Upon locating the desired object, the need arises to replace it with an updated version. To accomplish this in JavaScript:
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);
This code snippet will find the object with the "name" property set to "string 1" and log it to the console.
Once the object is located, you can replace it with a modified version:
arr[arr.indexOf(obj)] = { name:"string 1", value:"updated value", other: "that" };
This code finds the index of the located object in the array using indexOf and replaces it with the modified object.
The above is the detailed content of How to Find and Replace an Object in a JavaScript Array Based on a Specific Property Value?. For more information, please follow other related articles on the PHP Chinese website!