I am trying to create a function that will copy all properties from a source object and paste them to a destination object. I want to create a deep copy, so I am not using object.assign().
Here is my code:
var obj1 = {
arr: ['a','b','c','d'], // >= 4 elements, all should be truthy
obj: {a:1,b:2,c:3,d:4}, // >= 4 values, all should be truthy
halfTruthyArr: [null,'b',null,'d'], // >= 4 elements, half should be falsy
halfTruthyObj: {a:1,b:null,c:3,d:null}, // >= 4 values, half should be falsy
string: 'This is a string.',
reverseString: function (string) {
if (typeof string === 'string') return string.split('').reverse().join('');
}
};
var obj2 = {}
function extend(destination, source) {
destination = JSON.parse(JSON.stringify(source))
}
extend(obj2,obj1)
console.log(obj2)
if you are setting the value of an object or array inside of function it is Pass by Value. So you need to pass object by reference or try this
function extend(source) {
return JSON.parse(JSON.stringify(source))
}
var obj2=extend(obj1);
console.log("ext",obj2)
or pass by reference. In this case you are only changing the property inside of the object, not assigning a new value to the whole object
function extend(source, destination) {
destination.result = JSON.parse(JSON.stringify(source));
}
var destination = { result: {} };
extend(obj1, destination);
var obj2=destination.result;
console.log("ext", obj2);