bergman
bergman

Reputation: 185

Get data by array selector

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?

Upvotes: 0

Views: 40

Answers (2)

Wulf
Wulf

Reputation: 3898

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/

Upvotes: 1

Satpal
Satpal

Reputation: 133403

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

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

Upvotes: 0

Related Questions