1

I am trying to create an array of objects, however when I am pushing onto my array it is adding a reference to the object rather than copying the values.

var nestedOrgList = [];
var tempTopOrg = {};

var i = 0;
while (typeof divList[i] !== 'undefined') {
    tempTopOrg.org = divList[i++]; // increment i after we assign this
    tempTopOrg.suborgs = [];

    while ($(divList[i]).has('.expand').length < 1 && i < divList.length) {
        tempTopOrg.suborgs.push(divList[i++]);
    }

    nestedOrgList.push(tempTopOrg);
};

Is there a better way to do this? Or do I need to do a manual copy?

nestedOrgList[insertIndex].org = tempTopOrg.org;
// etc..
insertIndex++;
digitalextremist
  • 5,952
  • 3
  • 43
  • 62
Troy Cosentino
  • 4,658
  • 9
  • 37
  • 59
  • @NuclearGhost JavaScript passes *values* (hint: objects *are* values) and, just like during an assignment, those *values* are *not* copied/cloned/duplicated in the process. There is *no* use of "reference" describing this behavior in the ECMAScript specification. – user2864740 Jan 28 '14 at 02:01

4 Answers4

2

You can check the following answer

How do I correctly clone a JavaScript object?

The JSperf

http://jsperf.com/cloning-an-object/82

definitely JavaScript should have a way natively to copy references.

Community
  • 1
  • 1
bipsa
  • 351
  • 2
  • 8
0

A common method if speed is not a critical goal is to encode/decode the object using JSON:

var json = JSON.stringify(tempTopOrg);
nestedOrgList.push( JSON.parse(json) );
Matt
  • 20,108
  • 1
  • 57
  • 70
0

javascript passes objects and arrays by reference, so you will have to make a copy before pushing,

myarray.push(JSON.parse(JSON.stringify(obj)));

is quick and dirty and probably has performance issues,

this question tries to tackle cloning of objects.

Community
  • 1
  • 1
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
0

to make a deep copy use

var newcopy = temp.slice(0);

and to filter undefined and null values use

newcopy  = newcopy.filter(function(e){ return e });
MZH
  • 1,414
  • 4
  • 29
  • 57