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

5
  • Where does item1, item2 and item3 come from? Commented May 5, 2016 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. Commented May 5, 2016 at 13:54
  • Thanks how would I do that? Commented May 5, 2016 at 13:55
  • 1
    Possible duplicate of What is the most efficient way to clone an object? Commented May 5, 2016 at 13:57
  • 1
    Thanks that worked, if you put it as an answer I can mark as correct Commented May 5, 2016 at 14:06

1 Answer 1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.