Troy Cosentino
Troy Cosentino

Reputation: 4778

javascript array push value of object

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++;

Upvotes: 1

Views: 168

Answers (4)

bipsa
bipsa

Reputation: 351

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.

Upvotes: 2

MZH
MZH

Reputation: 1534

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

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42746

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.

Upvotes: 0

Matt
Matt

Reputation: 20796

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

Upvotes: 0

Related Questions