If I want to clone an array, I can use the slice() function, but what if I want to "clone" a single element? I want to do something like this:
array1[i] = array2[i];
but I want to copy the value, not the reference. How can I do this? Also, will the solution work for associative arrays too? For example:
array1["one"] = array2["one"];
Thank you in advance.
You could use Object.assign and Array.splice
var cloneItem = Object.assign({}, array1[i]);
array2.splice(i, 0, cloneItem);
EDIT
The previous adds a clone item in the position, pushing the rest of the elements to the right. If you simply want to replace just do
array2[i] = Object.assign({}, array1[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With