I want to merge two A3 Objects together which contain some of the same Keys but different values. I've found many posts regarding adding two Objects together but I want to merge the two objects together so if the second object has different values they take priority. I have two Objects below:
_propsObj = new Object();
_propsObj.baseColour = 0x303237;
_propsObj.animation = false;
_propsObj.font = "Verdana";
_propsObj.fontColour = 0xffffff;
_propsObj.baseFontSize = 14;
_propsObj2 = new Object();
_propsObj2.animation = true;
_propsObj2.fontColour = 0xffffff;
_propsObj2.baseFontSize = 10;
My desired ouput Object would accept the new values of the second Object but maintain the values of the first Object :
_outputObj.baseColour = 0x303237;
_outputObj.animation = true;
_outputObj.font = "Verdana";
_outputObj.fontColour = 0xffffff;
_outputObj.baseFontSize = 10;
I wasn't sure if I should be using Arrray.concat do this or if there is an easier solution? Any help would be appreciated.
the merge method hereunder
var _propsObj:Object = new Object();
_propsObj.baseColour = 0x303237;
_propsObj.animation = false;
_propsObj.font = "Verdana";
_propsObj.fontColour = 0xffffff;
_propsObj.baseFontSize = 14;
var _propsObj2:Object = new Object();
_propsObj2.animation = true;
_propsObj2.fontColour = 0xffffff;
_propsObj2.baseFontSize = 10;
var merged:Object = merge( _propsObj, _propsObj2 );
private function merge( obj0:Object, obj1:Object ):Object
{
var obj:Object = { };
for( var p:String in obj0 )
{
obj[ p ] = ( obj1[ p ] != null ) ? obj1[ p ] : obj0[ p ];
trace( p, ' : obj0', obj0[ p ], 'obj1', obj1[ p ], '-> new value = ', obj[ p ] );
}
return obj;
}
traces:
font : obj0 Verdana obj1 undefined -> new value = Verdana
fontColour : obj0 16777215 obj1 16777215 -> new value = 16777215
baseColour : obj0 3158583 obj1 undefined -> new value = 3158583
animation : obj0 false obj1 true -> new value = true
baseFontSize : obj0 14 obj1 10 -> new value = 10
the important line is :
obj[ p ] = ( obj1[ p ] != null ) ? obj1[ p ] : obj0[ p ];
it recursively creates the property on the new Object 'obj' and checks if that property is assigned on the 2nd object, if so it assigns the value of the second object to that property, otherwise it falls back to the value of that property on the first object.
NB: if a value is not set on the first object, it will not be looked up in the second object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With