-1

I'm trying the following code but It's behaving weird.

Code:

const a = [{ x: 'c', y: 'z' }, { x: 'd' }];

const b = a[0];
b.x = 'dx';

a.splice(1, 0, b)

console.log(a)

Output:

[{x: "dx", y: "z"},{x: "dx", y: "z"}, {x: "d"}]

But I want:

[{x: "c", y: "z"},{x: "dx", y: "z"}, {x: "d"}]

Please help me!

4 Answers4

3

you're accessing the object by reference, therefore you're changing the object itself from wherever you access it...

https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0

if you wanna make a clone array with the same values the easiest way is

const clone = [ ...original ]  
2
const b = a[0];

This does not make a copy of the object. It just creates a new reference to the same object. So when you modify the object on the next line:

b.x = 'dx';

... the single object now has a new x property. Your two references to the object will both "see" this change, because they're both pointing to the same object.

If you want to have two different objects, you'll need to make a copy. For your case, a shallow copy will suffice (shallow meaning only the top level properties will be copied). Either use spread syntax:

const b = { ...a[0] }

Or use Object.assign (this was the approach before spread syntax was added to the language):

const b = Object.assign({}, a[0]);
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

You can use a spread operator to create a new reference for the object :

const b = [
    ...a[0]
];

It's called "immutability" look it up !

  • 1
    if you google immutability you most likely find something different (which you should still read to understand what your doing)... google reference vs value javascript instead – Laurent Schwitter Jul 23 '20 at 14:56
-1

Just change it to the below code

const a = [{ x: 'c', y: 'z' }, { x: 'd' }];

const b = {x: a[0].x, y: a[0].y};
b.x = 'dx';

a.splice(1, 0, b)

console.log(a)
Yusuf Ipek
  • 166
  • 1
  • 11