Code Tip: Merge/Combine two objects into one

Ever wanted to combine properties of one object with another object resulting finally into one single object. Here is a little utility function which would help you do this:

private function combineVars ( defaultVars:Object, additionalVars:Object ):Object
{
var combinedObject :Object = {};
for ( var property:String in defaultVars )
{
combinedObject[ property ] = defaultVars[ property ];
}
for ( var property:String in additionalVars )
{
combinedObject[ property ] = additionalVars[ property ];
}
return combinedObject;
}

Advertisements
Code Tip: Merge/Combine two objects into one

One thought on “Code Tip: Merge/Combine two objects into one

  1. Tony says:

    Please correct me if I’m wrong, but I’m pretty sure this won’t work for two reasons:

    1. The var “property” is used twice in the same scope which will throw a duplicate definition error. It’s an easy fix by just renaming one of the vars.

    2. If the first loop cycles through all of “property” in the object, the value of “property” will be the incremental index number of each sub-object/value; When you get to the next loop, you’ll have an issue because you’re starting back at 0 and incrementing up, thus replacing the values you just created.

    The fix for the second problem is to create a number variable that equals 0 before both loops, and allow it to increment with the first loop. Then, in the second loop, add that number to your “property1” number so it doesn’t replace what the last loop set. Here’s my example:

    private function combineVars ( defaultVars:Object, additionalVars:Object ):Object
    {
    var n:Number = 0;
    var p:Number; //This var exists to typecast the value of the second loop’s var to make sure it’s a number.

    var combinedObject :Object = {};
    for ( var property:String in defaultVars )
    {
    combinedObject[ property ] = defaultVars[ property ];
    n++; // We’re counting up from 0 to create a number that offsets the second loop’s var.
    }

    for ( var property1:String in additionalVars )
    {
    p = Number(property1);
    combinedObject[ p+n ] = additionalVars[ property1 ];
    }
    return combinedObject;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s