3

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.

1
  • 1
    Your question is unclear, can you explain exactly what you want to do ? Commented Mar 29, 2014 at 7:51

1 Answer 1

1

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}]} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.