开发者

Combine/merge Dynamic Objects in AS3

I have 2 dyn开发者_如何学Pythonamic objects and I want to build one to contain all the properties:

var o1:Object = {prop1:val1,prop2:val2,prop3:val3};
var o2:Object = {prop3:val3a,prop4:val4};

and I need to obtain a third object that looks like that:

{prop1:val1, prop2:val2, prop3:val3a, prop4:val4};

Basically I need a way to iterate through the object properties and to add new properties to the third object. I have to mention I'm quite new to AS3/Flash/Flex.


First question, do you really mean to have prop3 in both objects? you will need to decide what to do in case of a collision like that, which object has precedence.

Secondly, check out the introspection apis: http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_8.html

something like this should work:

public function mergeDynamicObjects ( objectA:Object, objectB:Object ) : Object 
{
    var objectC:Object = new Object();

    var p:String;

    for (p in objectA) {
       objectC[p] = objectA[p];
    }

    for (p in objectB) {
       objectC[p] = objectB[p];
    }

    return objectC;
}

If the property exists in A and B, B's will overwrite A's. Also note that if the values of a property is an object, it will pass a reference, not a copy of the value. You might need to clone the object in those cases, depending on your needs.

Note: I haven't actually tested the above, but it should be close. Let me know if it doesn't work.

Updated to fix the errors. Glad it works for you though.


You can dynamically access/set properties on objects with the index operator. The for loop will itterate over the property names, so if you put it all together, the following test passes:

    [Test]
    public function merge_objects():void {
        var o1:Object = {prop1:"one", prop2:"two", prop3:"three"}; 
        var o2:Object = {prop3:"threeA", prop4:"four"};

        var o3:Object = new Object();

        for (var prop in o1) o3[prop] = o1[prop];
        for (var prop in o2) o3[prop] = o2[prop];

        assertThat(o3.prop1, equalTo("one"));
        assertThat(o3.prop2, equalTo("two"));
        assertThat(o3.prop3, equalTo("threeA"));
        assertThat(o3.prop4, equalTo("four"));
    }


you can iterate over the object properties like:

var obj1:Object = new Object();
for(var str:String in obj2){
    obj1[str] = "any value"; // insert the property from obj2 to obj1
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜