0

JS bin link

cosnt config = {a: {x: 1, y: 2, z: 3}, b: {x: 12, y: 23, z: 34}};

console.log(config);

// ->
// [object Object] {
//  a: [object Object] {
//    x: 1,
//    y: 2,
//    z: 3
//  },
//  b: [object Object] {
//    x: 12,
//    y: 23,
//    z: 34
//  }
// }

const items = [];
items.push(config['a']);

console.log(items);

// ->
// [[object Object] {
//  x: 1,
//  y: 2,
//  z: 3
// }]

items[items.length - 1].q = "mutation";

console.log(items);

// ->
// [[object Object] {
//  q: "mutation",
//  x: 1,
//  y: 2,
//  z: 3
// }]

console.log(config);

// ->
// [object Object] {
//  a: [object Object] {
//    q: "mutation",
//    x: 1,
//    y: 2,
//    z: 3
//  },
//  b: [object Object] {
//    x: 12,
//    y: 23,
//    z: 34
//  }
// }

console.log(config.a)

// ->
// [object Object] {
//  q: "mutation",
//  x: 1,
//  y: 2,
//  z: 3
// }

I understand that config.a is updating because items[0] is a reference to config.a

Still it doesn't make much sense to me why its designed this way.

I'm thinking about how to code this better so that it doesn't update config

sudo bangbang
  • 27,127
  • 11
  • 75
  • 77
  • Because these are references, when you change a reference value it will be reflected at all the places you're using that value, in case of one level deep you can do shallow copy else you will need deep copy – Code Maniac Sep 19 '19 at 09:53
  • If your question is how to deep copy (sometimes called clone) an object, then this is a duplicate of [*What is the most efficient way to deep clone an object in JavaScript?*](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/122704#122704) and many similar questions. – RobG Sep 19 '19 at 10:12
  • Yes, deep copy is one of the solution. In this case, shallow copy would also work. I was just confused about how this worked like this. I think the question I'm asking is different from the one you linked. – sudo bangbang Sep 19 '19 at 10:22

1 Answers1

0

JS bin link

items = [
           ...items.slice(0, items.length - 1),
          {...items[items.length -1 ], q: "mutation"}
        ];

This would create a new object that updating the reference.

sudo bangbang
  • 27,127
  • 11
  • 75
  • 77