Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript string to object reference (without eval() or indexes)

I've seen quite some related questions and google results, but none seem to match my problem.

I'm getting a string "header.h2" which I want to contencate to 'var objects'. So I want objects.header.h2 (which contains more hash data).

However, I don't want to use eval() or the often suggested buttons[] for the obvious reason that buttons[header.h2] won't work and I would need buttons[header][h2].

So how can I remain the object notation, or in the worst case, solve my problem?

like image 255
Gerben Jacobs Avatar asked Dec 21 '22 15:12

Gerben Jacobs


1 Answers

Just a quick sketch of a possible way:

Your data:

var data = [
    {foo: 1, bar: 2, foobar: [
        'a', 'b', 'c'
    ]},
    {foo: 1, bar: 2, foobar: [
        'd', 'e', 'f'
    ]},
    {foo: 1, bar: 2, foobar: [
        'g', 'h', 'i'
    ]}
];

var accessor = '1.foobar.2';

Using a helper function:

function helper(data, accessor) {
    var keys = accessor.split('.'),
        result = data;

    while (keys.length > 0) {
        var key = keys.shift();
        if (typeof result[key] !== 'undefined') {
            result = result[key];
        }
        else {
            result = null;
            break;
        }
    }

    return result;
}

Or making it available to all objects: (personally, I don't like this...)

Object.prototype.access = function (accessor) {
    var keys = accessor.split('.'),
        result = this;

    while (keys.length > 0) {
        var key = keys.shift();
        if (typeof result[key] !== 'undefined') {
            result = result[key];
        }
        else {
            result = null;
            break;
        }
    }

    return result;
};

Debug output:

console.log(
    helper(data, accessor), // will return 'f'
    data.access(accessor) // will return 'f'
); 
like image 159
Yoshi Avatar answered Dec 24 '22 05:12

Yoshi