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++;
1
  • @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. Commented Jan 28, 2014 at 2:01

4 Answers 4

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.

1
  • Thank you for the reference to that answer Commented Jan 28, 2014 at 2:28
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) );
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.

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 });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.