NokX
June 18, 2014, 7:13pm
1
I’m setting one array like so…
var myArray = [
{ 'Name' : 'Bob',
'Hats' : [
{ 'Color' : 'Green' },
{ 'Color' : 'Red' },
{ 'Color' : 'Blue' }
]
},
{ 'Name' : 'Tim',
'Hats' : [
{ 'Color' : 'Yellow' },
{ 'Color' : 'Purple' }
]
}
];
And then I set another variable with the contents of myArray like so…
var anotherArray = myArray.slice();
When I remove myArray[1], for example, anotherArray[1] stays the same. However, when I remove a Hat the hat is removed from both.
I’m assuming that slice() takes care of the top level arrays but the nested ones still are linked. Maybe?
Just trying to find a (hopefully) simple solution to stop the syncing. Thanks!
The problem is that Array.slice() does not create a deep copy (rather a shallow one) and is therefore not suitable for multidimensional arrays.
One way round this is to serialize the entire array to JSON and then de-serialize it back:
var myArray = [
{ 'Name' : 'Bob',
'Hats' : [
{ 'Color' : 'Green' },
{ 'Color' : 'Red' },
{ 'Color' : 'Blue' }
]
},
{ 'Name' : 'Tim',
'Hats' : [
{ 'Color' : 'Yellow' },
{ 'Color' : 'Purple' }
]
}
];
var anotherArray = JSON.parse(JSON.stringify(myArray));
myArray[0]["Hats"].pop();
console.log(myArray, anotherArray);
Ref: http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy
NokX
June 19, 2014, 2:44pm
3
James_Hibbard:
The problem is that Array.slice() does not create a deep copy (rather a shallow one) and is therefore not suitable for multidimensional arrays.
One way round this is to serialize the entire array to JSON and then de-serialize it back:
var myArray = [
{ 'Name' : 'Bob',
'Hats' : [
{ 'Color' : 'Green' },
{ 'Color' : 'Red' },
{ 'Color' : 'Blue' }
]
},
{ 'Name' : 'Tim',
'Hats' : [
{ 'Color' : 'Yellow' },
{ 'Color' : 'Purple' }
]
}
];
var anotherArray = JSON.parse(JSON.stringify(myArray));
myArray[0]["Hats"].pop();
console.log(myArray, anotherArray);
Ref: http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy
Gotcha. I figured it wasn’t digging in deep into the structure and I assumed there had to be an easier way. The way you showed is just what I needed. Thank you!