Estoy tratando de crear una función que copie todas las propiedades de un objeto de origen y las pegue en un objeto de destino. Quiero crear una copia profunda, por lo que no estoy usando object.assign().
Aquí está mi código:
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)si está configurando el valor de un objeto o matriz dentro de la función, es Pasar por valor. Por lo tanto, debe pasar el objeto por referencia o probar esto
function extend(source) { return JSON.parse(JSON.stringify(source)) } var obj2=extend(obj1); console.log("ext",obj2)o pasar por referencia. En este caso, solo está cambiando la propiedad dentro del objeto, no asignando un nuevo valor a todo el objeto.
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);