actionscript 3 - AS3 How to assign value of an array to the Keys of an object? -
i think eval-related.
here, have array of unknown length in run-time. say, example, wish assign values array keys of object, below:
var myarr:array = ['a','b','c',...]; //unknown length var finalvalue:int = 20; var myobj:object = new object(); assignvaluetoobject(); //logics of assignvaluetoobject function /* //todo.. black box */ //in end, myobj has value stored , can accessed myobj["a"]["b"]["c"][...] = 20;
i not sure if need resort eval.hurlant, wish there simple way of doing (either recursion or sth)
simply use loop iterate on elements of array , create objects except last element of array, should not object desired value. code untested.
var myarr:array = ['a','b','c',...]; //unknown length var finalvalue:int = 20; var myobj:object = new object(); // variable holdsthe msot created sub-object var currentobject = myobj; // create nested objects second last property name (var index:int = 0; index < myarr.length -1; ++i) { currentobject = currentobject[element] = {}; } // add value last property currentobject[myarr[myarr.length -1]] = finalvalue;
of course, if want insert many such values have check if nested object structure contains of properties avoid overriding existing ones.
i have looks quite convoluted , there's high chance actual problem trying solve can solved lot more elegantly having property names strings in array.
Comments
Post a Comment