Assign new value to item in an array if it matches another item without looping in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

For this, use filter() along with map(). Let’s say the following is our array −

const studentDetails = [
   {Name: "John"},
   {Name: "David"},
   {Name: "Bob"},
   {Name: "Mike"}
]

We will assign a new value to the name “Bob”. Following is the code −

Example

const studentDetails = [
   {Name: "John"},
   {Name: "David"},
   {Name: "Bob"},
   {Name: "Mike"}
]
var changeName = "Bob";
studentDetails.filter((obj) => obj.Name === changeName).map((obj) =>
obj.Name = "Carol");
console.log(studentDetails);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo98.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo98.js
[
   { Name: 'John' },
   { Name: 'David' },
   { Name: 'Carol' },
   { Name: 'Mike' }
]
raja
Updated on 07-Sep-2020 08:39:21

Advertisements