0

I need to clone a data from JSON a key of array, and then edit the newly added key.

Here's the full code i used :

var test_arr = [{'name' : 'data','item':'data2'},{'name' : 'helw','item':'data3'}];
var test_arr1 = test_arr[1];
test_arr.push(test_arr1);
index = 2;
var datas = test_arr[index];
datas.name = 'janjan';
console.log(test_arr);

From the code above, i copied test_arr[1] and pushed it into the test_arr, creating a new index,

I successfully added a new index on test_arr (test_arr[2]) but when i edit test_arr[2], it also edits test_arr[1].

[
  { name: 'data', var2: 'data2' },
  { name: 'janjan', var3: 'data3' },
  { name: 'janjan', var3: 'data3' }
]

Is there a way to only edit test_arr[2] only?

  • You are not adding a *new* object but the same object *again*. By editing index 1 you are editing the same object as index 2. The index keys are references to the values in the array. – Emiel Zuurbier Sep 01 '20 at 06:07
  • Remove `var datas` and use: `test_arr[index].name = 'janjan'` – Aks Jacoves Sep 01 '20 at 06:10

1 Answers1

2

Actually you are doing shallow copy of object. That's why it change the value of object which you used to copy.

You need to consider deep copy of JSON object you just need to modify 2nd line

var test_arr = [{'name' : 'data','item':'data2'},{'name' : 'helw','item':'data3'}];
var test_arr1 = JSON.parse(JSON.stringify(test_arr[1]));
test_arr.push(test_arr1);
index = 2;
var datas = test_arr[index];
datas.name = 'janjan';
console.log(test_arr);
WaqarAli
  • 173
  • 10