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?

3
  • delete data.id but this would delete the property from dataNew too. You need to clone the object before doing that. Commented Nov 14, 2017 at 8:53
  • @Werner, How can I clone the object? Commented Nov 14, 2017 at 8:53
  • 1
    const dataNew = Object.assign({}, data) Commented Nov 14, 2017 at 8:54

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.