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

5

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

8 Comments

Seriously, you don't think there are at least 50 dups of this question?
@jfriend00: Sometimes it's quicker to just answer than find a good dupe. If I have time I'll find a dup
@jfriend00: I know a good answer for function arguments but I don't know of one for just variables.
@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.
@jfriend00: The answer you duped is another good example of not a good answer for this question. It's a different (but related) question.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.