0

I have the following problem :

var a = {
    'a': '',
    'b': ''
},

b = [1,3],
o = {};

for (i = 0; i<b.length; i++) {
    o['shop' + b[i]] = a;
    o['shop' + b[i]].store = b[i];
}

console.log(JSON.stringify(o));

Expecting shop[n] will be equal to store value, but it's wrong

{
    "shop1" : {
        "a" : "",
        "b" : "",
        "store":3
    },
    "shop3" : {
        "a" : "",
        "b" : "",
        "store":3
    }
}

What's wrong with it?

1
  • what do u mean by "store value" Commented Nov 29, 2017 at 7:10

1 Answer 1

2

Because you have a single object to which a refers and when changing it via each iteration you actually change the value for all of them, because you work with the reference which refers to the single object. You can use Object destructing to copy the object for each property in the o.

var a = {
    'a': '',
    'b': ''
};
var b = [1,3];
var o = {};

for (var i = 0; i < b.length; i++) {
    o['shop' + b[i]] = {...a};
    o['shop' + b[i]].store = b[i];
}

console.log(JSON.stringify(o));

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

4 Comments

I don't understand how to fix it. If I redefine it var aa = a, it doesn't work too.
You need to copy the actual object to which a refers - into another object which { ...a } does. var aa = a is just another reference to the actual object. I think you need to look at objects and how they are stored in the memory
Worth noting that Object destructing has a quite limited support at the current state.
Instead you can use Object.assign

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.