0

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)
  1. 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?
  2. The reverseString method in obj1 does not get copied using JSON.stringify. Why is this?
mattdags
  • 1
  • 2
  • 1
    Does this answer your question? [How to deep merge instead of shallow merge?](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge) – Nick Bailey Mar 14 '22 at 19:20
  • "`undefined`, `Function`s, and `Symbol`s are not valid JSON values. If any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array)" https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description – Daniel Beck Mar 14 '22 at 19:38

1 Answers1

0

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);
Serge
  • 40,935
  • 4
  • 18
  • 45