0

I have a dictionary called dict with three variables

Then I have an array that has to include the dictionary but add a new variable to it called name each time.

Now at the end all the names are becoming equal, how would I get around this problem?

dict = {"a" :1, "b" : 2, "c" : 3};
items = [];
item1.tempdict = dict;
item1.tempdict.name = 4;
item2.tempdict = dict;
item2.tempdict.name = 5;
item3.tempdict = dict;
item3.tempdict.name = 6;

thanks

ManoDestra
  • 6,325
  • 6
  • 26
  • 50
Adam Katz
  • 6,999
  • 11
  • 42
  • 74
  • Where does `item1`, `item2` and `item3` come from? – Joseph May 05 '16 at 13:54
  • You would need to clone the dict object each time. You're overwriting the same object instance when you change the values. Each of the items (item1, item2, item3) have the dict object stored in their tempdict variable reference. So, change any of those values and it will simply change the singleton dict object. – ManoDestra May 05 '16 at 13:54
  • Thanks how would I do that? – Adam Katz May 05 '16 at 13:55
  • 1
    Possible duplicate of [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – ManoDestra May 05 '16 at 13:57
  • 1
    Thanks that worked, if you put it as an answer I can mark as correct – Adam Katz May 05 '16 at 14:06

1 Answers1

1

The issue is that you're creating the dict object and then simply adding references to that single dict object in each of your item objects. You need to clone the dict object each time you append it to an item, to get a cloned version of it.

Information on how to do that can be found here.

One possible way to do that, from the above link, for basic bean objects without functions, is to use this technique:

var clonedObject = JSON.parse(JSON.stringify(objectToClone));

There are other ways of doing it though if your object is well known and can be easily recreated, via a constructor function for example. Hope that helps :)

Community
  • 1
  • 1
ManoDestra
  • 6,325
  • 6
  • 26
  • 50