|
-
[RESOLVED] How do you duplicate an object?
duplicating an object doesn't seems to work if the original object contains an array. Is there a way around this? Here's my code:
Code:
var originalObj:Object = {people: [{nm: "max"}], age:41, city:"Los Angeles"}
var newObj:Object = new Object()
// I copy all properties of the original object into the newObj
for (var a:String in originalObj) newObj[a] = originalObj[a]
// traces out as expected
trace("name and ages are the same: "+originalObj.people[0].nm+" "+newObj.people[0].nm+" "+originalObj.age+" "+newObj.age)
// I make a change in the array property of the newObj
newObj.people[0].nm = "Kadin"
// I make a change to the number property of the newObj
newObj.age = 4
// the number property works as expected but the change to the array is applied to both the originalObj & newObj objects
trace("names are same but ages are not "+originalObj.people[0].nm+" "+newObj.people[0].nm+" "+originalObj.age+" "+newObj.age)
Any ideas?
-
Total Universe Mod
When you clone the array portion you're just passing a pointer to that exact place in memory. Lists are only passed by reference unlike primitives like strings or numbers which passed by value.
You're going to have to make a deep copy of your original object.
Code:
var originalObj:Object = {people: [{nm: "max"}], age:41, city:"Los Angeles"};
var newObj:Object = myCustomClone(originalObj);
function myCustomClone(obj:Object):Object{
var temp:Object = {};
var people:Array = [];
for(var i:int = 0; i < obj.people.length; i++){
people.push({
nm: obj.people[i].nm
});
}
temp.people = people;
temp.age = obj.age;
temp.city = obj.city;
return temp;
}
-
almost there
Thanks jAQUAN this points me in the right direction. The only problem is the object I'll be cloning will be dynamic. I won't know the name of the array or if there will always be an array. Any ideas on how I would handle that?
-
I found an awesome solution:
//Clones an object filled array, multi-dimensional arrays, or complex object
private function clone(source:Object):*
{
var myBA:ByteArray = new ByteArray();
myBA.writeObject(source);
myBA.position = 0;
return(myBA.readObject());
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|