-1

In JavaScript, if you do this

var x = {
    "propname with whitespace": "val1",
    "other propname": "val2"
};

var y = x;

and then do this

delete y["propname with whitespace"];

Will cause x to also lose its propname with whitespace property. How to delete a property from y without affecting x while still supporting whitespaces in a property name?

starleaf1
  • 2,701
  • 6
  • 37
  • 66

2 Answers2

3

This is because x and y are both references to the same value in memory, see this StackOverflow question.

However, you can use Object.assign() to create a shallow copy of an object:

var x = {
    "propname with whitespace": "val1",
    "other propname": "val2"
};

var y = Object.assign({}, x);
delete y["propname with whitespace"];

console.log(y);
doubleOrt
  • 2,407
  • 1
  • 14
  • 34
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • You're answer will work in this situation, but cannot perform a deep clone. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign. But still, I learned something new with the Object.assign() – Stephen Agwu Dec 05 '17 at 10:18
-2

Edit Just ran into a problem where I needed to copy and object and neither my solution below nor the accepted solution worked. This is because neither solution can perform a deepclone (when a property value is set as an object). Check out the warning in the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Correct answer for a deep clone situation would be

y = {'a':2,'b':3}
z = JSON.parse(JSON.stringify(y))

This will solve the deep clone problem: like if y = {'a':{'c':4},'b':3}

End Edit

As Pranav put in the comments, both variable reference the same object. So what happens to one, happens to the other. To fix this you would have to create a copy of y without it referencing x:

y = {'a' : 2,'b': 3}
z = Object.keys(y)
let x = {}
z
for (i in z) {
  x[z[i]] = y[z[i]]
}

Now:

delete y["a"]
y = {"b":2}

And:

x = {"a":1, "b":2}

The big takeaway here is that you have to create new object that looks exactly like y, but that doesn't reference y.

Stephen Agwu
  • 1,013
  • 2
  • 15
  • 29
  • Your example is not working, and the use of `for..in` with arrays is not encouraged. – doubleOrt Nov 30 '17 at 17:27
  • Whoops, missed the y[z[i]]. Should work now. Shouldn't be a problem to refactor so that it doesn't use for..in (though in this and most cases I don't see the problem. At the heart of is, your question does get answered though... – Stephen Agwu Nov 30 '17 at 17:46
  • why use Object.keys? Just use `for in` on original object to do it old school way – charlietfl Nov 30 '17 at 18:02
  • lol, true, I was doing something else when I came accross this and had object.keys on the brain. – Stephen Agwu Nov 30 '17 at 18:14
  • Also your answer is much better, I don't think I've ever used object.assign – Stephen Agwu Nov 30 '17 at 18:15