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)
- obj2 is not changed using the function. I understand the function uses pass by reference, which is why the object is not reassigned. Is there a way around this so that the object I pass in as a parameter is edited?
- The reverseString method in obj1 does not get copied using JSON.stringify. Why is this?