0

As we know its possible to access field by name using indexer.

var obj:* = {name:"Object 1"}; trace(obj["name"]); // "Object 1" 

But how to access an array element by String?

var arr:Array = new Array(); var obj:* = {items:arr}; trace(obj["items[0]"]); // Undefined 

1 Answer 1

2

Ok, basically you want to be able to have a string be interpreted as actionscript. No elegant solution I'm afraid. You could write a parser that handles some simple syntax in a string and retrieves the value.

Here's a simple example:

var obj:Object = { items:[1, 2, 3], subObj: { subitems: [4, 5, 6] } }; trace(getValueInObject(obj, "items[0]")); // 1 trace(getValueInObject(obj, "subObj.subitems[2]")); // 6 // takes an object and a "path", and returns the value stored at the specified path. // Handles dot syntax and [] function getValueInObject(obj : Object, pathToValue : String) : * { pathToValue = pathToValue.replace(/\[/g, ".").replace(/]/g, ""); var pathFractions : Array = pathToValue.split("."); var currentObject : Object = obj; while (pathFractions.length > 0 && currentObject != null) { var fraction : String = pathFractions.shift(); currentObject = currentObject[fraction]; } if (currentObject != null) { return currentObject; } return null; } 
Sign up to request clarification or add additional context in comments.

3 Comments

I need something like this 'obj["items"][0]'. I know how to access array... -1
I have updated my original answer with a possible solution, I hope it's to some use.
That's what i though. Ty!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.