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

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

Patricia Arquette
Release: 2024-11-28 01:50:14
Original
760 people have browsed it

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

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" }
];
Copy after login

Modifying the Found Object:

Upon locating the desired object, the need arises to replace it with an updated version. To accomplish this in JavaScript:

Finding the Array Element:

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);
Copy after login

This code snippet will find the object with the "name" property set to "string 1" and log it to the console.

Replacing the Object:

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" };
Copy after login

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!

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