-3

How do I make obj2 the same as obj1 but not affected by the deletion?

Currently the name: 42 entry will be deleted from both objects.

Is it because of hoisting - that is, the deletion occurs before obj2 is created?

var obj1 = {
 'name': 'John',
 'age': 42,
}

var obj2 = obj1

delete obj1['name']

console.log(obj1)
console.log(obj2)
barciewicz
  • 3,511
  • 6
  • 32
  • 72
  • assigning doesn't make a copy. https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object – zmag Feb 22 '19 at 15:48
  • 3
    Use `Object.assign` to copy, then do whatever you need. – Seblor Feb 22 '19 at 15:48
  • 2
    `var obj2 = {...obj1};` – Jonas Wilms Feb 22 '19 at 15:49
  • If you simply assign an object to a variable JavaScript will copy it by `reference`. It means that both variables are pointing to the same object. You really need to create a new object with the same properties as your target object. Possible duplicate [How do I correctly clone a JavaScript Object](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Alberti Buonarroti Feb 22 '19 at 15:49
  • @JonasWilms it won't work with some objects like window. – Zydnar Feb 22 '19 at 15:52
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Feb 22 '19 at 15:57

2 Answers2

4

Please use the following

var obj2 = Object.assign({}, obj1)

Documentation

Please note that this is not the deep copy or a copy of an object with all the possible properties (it is explicitely stated in the doc attached above)

nesteant
  • 1,070
  • 9
  • 16
  • And for the complicated object. We can use `_.cloneDeep(obj)` from `lodash` or using `JSON.parse(JSON.stringify(obj))` to clone a new object. – bird Feb 22 '19 at 16:04
0

You can use spread operator of ES6 as:

let obj2 = {...obj1};

Read more about spread operator here

What's wrong in your code?

Actually, when you are assigning the obj1 to obj2 the reference of obj1 and obj2 will become the same i.e., both will share the same memory location address.

Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65