Object.assign is used for merging object & cloning purpose.
Merging Objects in JavaScript
var o1 = { a: 1 };
var o2 = { b: 2,a:5 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 5, b: 2, c: 3 }
console.log(o1); // { a: 5, b: 2, c: 3 }, target object itself is changed.
console.log(o2); // {b: 2,a:5 }
console.log(o3); // { c: 3 }
Here we are merging o1,o2,o3 object during merge o1 also get merged object value along with returned object "obj". 'a' happens to be in o1 & o2 so in merged object a get value from last object with a defined in it based on sequence in which they comes in Object.assign.
Copying Object
Though object.assign copies object deep clone is not happening.
var obj2 = Object.assign({ p: 67 }, { q: 09 }, { r: 34 });
console.log(obj2);
let obj3 = {person: 'Thor Odinson',adr:{city:"mumbai"}};
let clone = Object.assign({}, obj3);
obj3.person ="test"
obj3.adr.city="kolkota"
console.log(clone);
console.log(obj3);
obj3 adr-->city in copied to "clone" by reference unlike key "person".so deep coping is not happening ,change in source adr-->city will modify in cloned object also.
Deep Clone:
let obj4 = {person: 'Thor Odinson',adr:{city:"mumbai"}};
let deep_clone = JSON.parse(JSON.stringify(obj4))
obj4.adr.city="pune"
console.log(deep_clone);
console.log(obj4);
Deep clone is possible using JSON.parse(JSON.stringify()) call on object.
Shallow Copy Example:
var employeeDetailsOriginal = { name: 'Manjula', age: 25, Profession: 'Software Engineer' };
var employeeDetailsDuplicate = employeeDetailsOriginal; //Shallow copy!
employeeDetailsDuplicate.name = 'NameChanged';
console.log(employeeDetailsOriginal);
console.log(employeeDetailsDuplicate);
Output:
{ name: 'NameChanged', age: 25, Profession: 'Software Engineer' }
{ name: 'NameChanged', age: 25, Profession: 'Software Engineer' }
Ellipses in Javascript:
var obj33 =[{a:4,b:7},{p:6,q:5}]
var obj5 = [... obj33];
obj33[0].a =44
console.log(obj5);
console.log(obj33);
object array copied using ellipses syntax also not deep clone.
Copying property by looping:
var person = {
name: 'John',
age: 28,
adr:{state:"maha"}
};
var newPerson = new Object();
for(prop in person){
newPerson[prop] = person[prop];
}
newPerson.adr.state="karnataka"
newPerson.age = 30
console.log(newPerson === person)
console.log(person)
copying property by looping in object also do not deep clone.
No comments:
Post a Comment