Link to home
Start Free TrialLog in
Avatar of Conrado ZAVALA
Conrado ZAVALAFlag for Honduras

asked on

Copy an array of an array, not by reference.

Dear Experts,

I have an array (parentarray) that contains another array (childarray) and I need to copy the array that is the child of my parent array.
For example:

parentarray[0].fname="Joe";  
parentarray[0].lname="Smith";
parentarray[0].childarray[0].eyescolor="blue";
parentarray[0].childarray[0].haircolor="blue";

I need to copy to a new array just the childarray but not by reference, I need an exact copy of the child array.
How could this be done?

Thanks in Advance.
Avatar of leakim971
leakim971
Flag of Guadeloupe image

parentarray[0].fname="Joe";  
parentarray[0].lname="Smith"; 
parentarray[0].childarray[0].eyescolor="blue";
parentarray[0].childarray[0].haircolor="blue";

var newChild = {};
for(var j in parentarray[0].childarray) {
   newChild[j] = parentarray[0].childarray[j];
}

// checking :
alert(JSON.stringify(newChild));

Open in new window

Avatar of Conrado ZAVALA

ASKER

Hi leakim971,

I know the length of the child array, let's suppose it is 3 (the child array is from 0 to 2) and I need to copy just the last element of that array.

How can use that code for copying just the last element of the array.

Thanks in Advance.
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much.
just fyi you can use slice which does the same thing without the loop;
var newChild=parentarray[0].childarray.slice(0);

Open in new window

test page : http://jsfiddle.net/u60fx11c/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Description
slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.
For strings and numbers (not String and Number objects), slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.