This question has already been answered:

Hello! Help copy and modify an element in an array. When I copy everything is fine, but as soon as I update 2 elements change. The one that copied and the one from which copied.

There is such an example:

$(function() { var element = [ {"id":1, "name":"test1"}, {"id":2, "name":"test2"}, {"id":3, "name":"test3"}, {"id":4, "name":"test4"}, {"id":5, "name":"test5"} ]; $("#clone").on("click", function(){ element.push(element[1]); }); $("#update").on("click", function(){ element[5]["name"] += " update"; //Изменяется новый элемент и элемент с id 2 console.log(element); }); }); 

I also try to change:

 element.push(element[1]); 

on:

 element[element.length]=element[1].slice(); 

I get the error: element [1] .slice is not a function

Reported as a duplicate at Grundy. javascript Aug 3 '17 at 12:25 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

     $(function() { var element = [{ "id": 1, "name": "test1" }, { "id": 2, "name": "test2" }, { "id": 3, "name": "test3" }, { "id": 4, "name": "test4" }, { "id": 5, "name": "test5" } ]; var elementCopy; $("#clone").on("click", function() { elementCopy = JSON.parse(JSON.stringify(element)); elementCopy.push(JSON.parse(JSON.stringify(element[1]))); }); $("#update").on("click", function() { elementCopy[5]["name"] += " update"; //Изменяется новый элемент и элемент с id 2 console.log({ 'Исходный массив ': element }); console.log({ 'Копия массива ': elementCopy }); }); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="clone">Clone</div> <div id="update">Update</div> 

    • And how to change the source array? - Jony Kook
    • @JonyKook only change the original by itself. When you copy an array through slice original array does not change - at the time of copying you get two different arrays with the same values. - Alexander Bragin
    • @JonyKook why minus? Say that I did not understand the question correctly - I will correct it. Or are they moderators? .. - Alexander Bragin
    • This is not me minus set - Jony Kook
    • one
      Thank you very much! You really helped !! - Jony Kook