Skip to content

AS3: Copying object properties to other objects

2010 July 2
tags: ,
by Tedb0t

Say you want to copy all the properties of an object to another object, but you can’t just assign it because they’re different types:

var requestVars:URLVariables = new URLVariables();
var myObject:Object = {prop1:"someValue"};
requestVars = myObject; // Throws type mismatch error

So you need to iterate through the properties of the source object and assign them to the target. You can do this with AS3’s array-like property access syntax:

for (var prop in myObject) requestVars[prop] = myObject[prop];
trace(requestVars.prop1); // prints "someValue"

Easy! Now sometimes you might need to do something similar with an XML file, say, a configuration file with a bunch of properties that you want to automatically assign to a local object:

var configXML:XML =
<configXML>
  <paths>
    <host>www.something.com/</host>
    <list>list</list>
    <recent>recent/</recent>
    <liked>liked/</liked>
  </paths>
</configXML>;

var paths:Object = new Object();

for each (var val in configXML.paths.*) paths[val.name()] = val;

trace(paths.host); // prints "www.something.com/"

You now have a plain Object instance with all the properties of the XML tree. Bing!

Related Posts:


One Response
  1. radistao permalink
    September 18, 2012

    This works only for object with dynamic properties. For class properties you need to use ObjectUtil.getClassInfo().properties array

Comments are closed.