2

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.

Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
Haito
  • 2,039
  • 1
  • 24
  • 35
  • 1
    If you assign an object to another variable, you are not cloning the object, instead, both variables will contain the same reference to the same data in memory. Therefore, you must clone the objects. See http://stackoverflow.com/q/122102/1529630 and http://stackoverflow.com/q/728360/1529630 – Oriol Oct 25 '14 at 17:20

2 Answers2

2

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Can you post example of your array you want to copy? Looks like I confused and you need to copy `tablicaZnacznikow`. In this case try `tablicaZnacznikow.map(function(el) { ... });`. – dfsq Oct 25 '14 at 17:43
0

All you have to do is to make an deep copy of your array (e.g. with jQuery):

var placeholder = $.extend(true, [], tablicaZnacznikow);
friedi
  • 4,350
  • 1
  • 13
  • 19