1

I have an object "a" and would like to duplicate it to "b" When I delete an element in "a" why is "b" also being affected?

var a  = {'apple':1,'orange':2,'grapes':3}
var b = a 

console.log(a,b)
delete b.apple
console.log(a,b)

Now a and b are the same. I only want the element in b to be deleted. How can I do this

Kaippally
  • 96
  • 10
  • 3
    This is a dup of many other answers. I will go find a dup to mark it as such. – jfriend00 Nov 01 '15 at 08:51
  • 1
    The reason is that `a` and `b` are both _references_ to the same object. You need to _clone_ the object to get what you need. See http://stackoverflow.com/q/122102/2170192. – Alex Shesterov Nov 01 '15 at 08:52
  • 1
    This question is not a dupe of the one linked. – slebetman Nov 01 '15 at 09:09
  • Note that the linked question explains the mechanism of passing the value to a function. Not the values themselves which is what this question is asking. – slebetman Nov 01 '15 at 09:10
  • @slebetman - I could literally find twenty dups that explain this. Here's another one: http://stackoverflow.com/a/11837596/816620 and http://stackoverflow.com/questions/7576884/will-this-copy-the-object-or-add-a-reference-to-it/7576991#7576991 and http://stackoverflow.com/questions/30427395/object-or-objectification/30427746#30427746 and http://stackoverflow.com/questions/13595359/assigning-a-var-to-temp-var-doesnt-stop-origianal-var-from-changing/13595387#13595387 – jfriend00 Nov 01 '15 at 09:12

1 Answers1

2

Objects and arrays in javascript are references. So when you do:

var b = a;

You're making another pointer to object a. You're not copying a.

If you want to make a copy of an object you can use Object.create:

var b = Object.create(a);
slebetman
  • 109,858
  • 19
  • 140
  • 171
  • 2
    Seriously, you don't think there are at least 50 dups of this question? – jfriend00 Nov 01 '15 at 08:55
  • 1
    @jfriend00: Sometimes it's quicker to just answer than find a good dupe. If I have time I'll find a dup – slebetman Nov 01 '15 at 09:01
  • @jfriend00: I know a good answer for function arguments but I don't know of one for just variables. – slebetman Nov 01 '15 at 09:03
  • @jfriend00: The answer pointed to by Alex above is a good example of not a good general purpose answer because it's jQuery specific. Even the non-jQuery answers to that question don't explain the WHY, which is what this question is asking. – slebetman Nov 01 '15 at 09:07
  • @jfriend00: The answer you duped is another good example of not a good answer for this question. It's a different (but related) question. – slebetman Nov 01 '15 at 09:10
  • `Object.create` does **not** make a shallow copy. –  Nov 01 '15 at 12:45
  • @torazaburo: Ah, I thought it did. Deleting that part of the answer. – slebetman Nov 02 '15 at 00:30
  • @slebetman Thank you buddy. **You** actually solved my problem – Kaippally Nov 02 '15 at 08:59