javascriptarraysjavascript-objectsjquery-gmap3

JavaScript copying object arrays


I tried copying an array of objects and i failed terribly. Every time I ended up with an array of references to original aray.

I tried ".concat()", I used "for" copying every element separately, but every time I made change in temporary array, original array changed too.

Here's the code.

Glossary:
tablicaZnacznikow - original array
placeholder - temporary array 
tempClosest - id of closest marker
startingPointID - id of marker from witch i start calculation
.meta field - defines if marker has been added to polyline

var placeholder = tablicaZnacznikow.concat();
            var tempArrayOfSomething = [placeholder[startingPointID].latLng];
            for (var i = 0; i < placeholder.length; i++) {
                var tempClosest = findClosestMarkerToAnotherMarker(placeholder, startingPointID);
                tempArrayOfSomething.push(placeholder[tempClosest].latLng);
                startingPointID = tempClosest;
                placeholder[tempClosest].meta = "USED";
                console.log(tempClosest);
            }

I use this code to make an array for making a path for gMap3 polyline. Thanks in advance.


Solution

  • In order to clone array of objects you can simply use map method and return object copy in each iteration. Very convenient that making a object copy is very simple with $.extend. All together:

    var newArr = tablicaZnacznikow.map(function(el) { 
        return $.extend({}, el);
    });
    

    or even shorter:

    var newArr = tablicaZnacznikow.map($.extend.bind(null, {}));
    

    That's it. map creates a new array, and $.extend clones objects. You get a clone resulting array of objects.

    Note: I used two ES5 methods which are supported from IE9+. If you also support older IE's simply use $.map instead of Array.prototype.map and $.proxy instead of Array.prototype.bind.