Reputation: 4938
I have the following code.
var emp={"EmployeeLists":[{"ID":1,"NAME":"Anbu","Salary":80000},{"ID":2,"NAME":"Anand","Salary":90000}]};
// Inserting a new object into EmployeeLists
emp.EmployeeLists.splice(2,0,emp.EmployeeLists[1])
console.log(JSON.stringify(emp));
Output: {"EmployeeLists":[{"ID":1,"NAME":"Anbu","Salary":80000},{"ID":2,"NAME":"Anand","Salary":90000},{"ID":2,"NAME":"Anand","Salary":90000}]}
// Modifying inserted object NAME Anand into MANI
emp.EmployeeLists[2].NAME="MANI";
console.log(JSON.stringify(emp));
Output: {"EmployeeLists":[{"ID":1,"NAME":"Anbu","Salary":80000},{"ID":2,"NAME":"**MANI**","Salary":90000},{"ID":2,"NAME":"**MANI**","Salary":90000}]}
After added a new object. I tried to modify the name of that object Anand to MANI but it is modified name of object Two and Three.
Upvotes: 3
Views: 49
Reputation: 9344
Great question! What you are seeing is underlying sharing of objects, because Javascript secretly treats objects like pointers in C if you are not careful. Let's rewrite this to make a clone of the object instead. We will use this previous Stackoverflow answer (cloning objects in Javascript is annoying to do in full generality).
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
emp.EmployeeLists.splice(2, 0, clone(emp.EmployeeLists[1]));
emp.EmployeeLists[2].NAME = "MANI";
// {"EmployeeLists":[{"ID":1,"NAME":"Anbu","Salary":80000},{"ID":2,"NAME":"Anand","Salary":90000},{"ID":2,"NAME":"MANI","Salary":90000}]}
Upvotes: 1