Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Assign New Value to Item in Array Without Looping in JavaScript



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' }
]
Updated on: 2020-09-07T08:39:21+05:30

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements