1

My javascript code like this :

var data= {product_id: 4, name: 'nike'}
console.log(data)

var dataNew = data
dataNew.id = 1

console.log(dataNew)

Demo is like this : https://jsfiddle.net/oscar11/69dw8dv1/

I append value in the object like that

The result of console.log(data) and console.log(dataNew) is there exist id

I want var data is no id

So there is only var dataNew that has id

How can I do it?

moses toh
  • 12,344
  • 71
  • 243
  • 443

1 Answers1

3

In JavaScript, object references are assigned, instead of the object values, unless the object is of primitive data types.

That's why dataNew and data refers to the same object when you do this:

var dataNew = data;

To prevent this, you need to create a copy of data like this:

var dataNew = Object.assign({}, data);

Now, the changes in dataNew won't affect data.

31piy
  • 23,323
  • 6
  • 47
  • 67