-1

I'm sorry for the low quality title but I don't know how to make it better (edits are welcome).

Look at this code example:

var a = {b: 1};
var c = {d: a, e: a};
c.d.b = 2;
alert(c.e.b); // 2 not 1

Like you can see in that code the result is 2 but I want it to be 1. It seems that my nestled dictionaries are sharing the same space in memory, but I want to "fix" that.

Obviously the easiest solution would not have any a dictionary.

var c = {d: {b: 1}, e: {b: 1}};

But I don't want this solution because I have to write several times {b: 1}.

Then I developed two solutions but I want to know which of them is better, or if there is something better even.

Class

class a { // or -> var a = class { //?
    constructor() {
        this.b = 1;
    }
}
var c =  {d: new a(), e: new a()};

Function

function a() { // or -> var a = function() { //?
    return {b: 1};
}
var c = {d: a(), e: a()};

Which of both is better? Or maybe any of both and the answer is another?

Ender Look
  • 2,303
  • 2
  • 17
  • 41
  • 1
    In Javascript, rather than dictionaries these are called objects, and it seems what you want to do is [clone or copy your object](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object), so hopefully that will be useful in researching answers to this question. – Khauri Jan 11 '18 at 22:37

2 Answers2

1

I'd probably use

var a = {b:1}
var c = {}
c.d = Object.assign({}, a)
c.e = Object.assign({}, a)

object.assign assigns all the properties of its second argument to the object in its first.

I feel this approach is quite intuitively similar to what you are doing in your first question, and also is a better solution if your a object is not something defined by you, for example from JSON.

Pinico
  • 74
  • 1
  • 1
  • 8
  • Do you know why you have to write `{}`? Could you explain that please? – Ender Look Jan 11 '18 at 22:46
  • 1
    As I said, `Object.assign` takes two arguments, takes all the properties of the second and assigns them to the first. the `{}` as the first argument is simply an empty object - it effectively copies all the properties into a brand new object, which ends up being the same as the first. – Pinico Jan 11 '18 at 23:07
0

Your example of implementing a class is a better one from my perspective.

Also there is a older way in javascript to remove all references by using JSON.parse(JSON.stringify(object))

In your case:

var a = {b: 1};
var c = {
    d: JSON.parse(JSON.stringify(a)),
    e: JSON.parse(JSON.stringify(a))
};
c.d.b = 2;
alert(c.e.b); // 1
Bogdan Bogdanov
  • 386
  • 1
  • 9