0

I have this original array objects:

const students=[
  { "name": "sean"},{"name":"paula"}
];

I am trying to update the object where student.name==="sean" to "jason"

I want to avoid update the original array object

console.log(students); // should be {"name": "jason"},{"name": "paula"}
console.log(findStudent); //output is {"name":"jason"} (desired result)

const students=[
  { "name": "sean"},{"name":"paula"}
];

const findStudent= students.find((student)=>student.name==="sean");
findStudent.name="jason";
console.log(findStudent); //output is {"name":"jason"} (desired result)
console.log(students); // output is {"name": "jason"},{"name": "paula"} (wrong result)

, how to avoid it?

yavgz
  • 275
  • 3
  • 17
  • What is the desired result for students? – Ando May 29 '23 at 21:56
  • @Ando `console.log(students); {"name": "sean"},{"name": "paula"} ` – yavgz May 29 '23 at 21:59
  • try doing this `var updatedStudents = students.map((student) => { if(student.name === "sean") { student.name = "jason"} return student }` then use the `updatedStudents` or assign it to `students` – Ando May 29 '23 at 22:06

0 Answers0