0

I want to get data from a data array by an array selector:

var sel = ["node1"]["node2"]["node3"];
var my_data = data_array[sel] //?!?

How to get a correct my_data?

4
  • show data array structure please Commented Jan 19, 2014 at 14:06
  • What is sel expected to look like? "node1node2node3" or "node1, node2, node3"? Commented Jan 19, 2014 at 14:07
  • the "sel" structure is always different, it depends on "data_array". Commented Jan 19, 2014 at 14:07
  • it should work like: var my_data = data_array["node1"]["node2"]["node3"]; Commented Jan 19, 2014 at 14:08

2 Answers 2

1

What about this idea?

Object.prototype.getBySelector = function(selector) {
    var currentElement = this;
    for (var i = 0; i < selector.length; i++) 
        currentElement = currentElement[selector[i]];
    return currentElement;
}

var sel = ["node1","node2","node3"];
var my_data = data_array.getBySelector(sel);

You can easily extend the getBySelector function by checking, if the nodes are existing and returning null, so no exception is thrown on an invalid selector.

See my jsfiddle: http://jsfiddle.net/U8YDQ/

Sign up to request clarification or add additional context in comments.

1 Comment

thats very nice. But expensive for my needs, since there is much data to process.
0

Its a wild-wild guess. You can try eval()

var sel = '["node1"]["node2"]["node3"]';
var my_data = eval('data_array' + sel);

3 Comments

i think this would work. I try not to use eval(). So i will do a workaround.
@bergman, it works see jsfiddle.net/U8YDQ/2. And do share what is your workaround
Hi thx for the fiddle. My workaround is passing the "data_array" around: var my_data = data_array["node1"]["node2"]["node3"]; :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.