Xear Xear - 1 year ago 103
jQuery Question

Alternative to eval() function due to minification

I would like to create an object this way:

var new_obj = {},
array_path = '',
the_value = 3;

array_path = '[\''fruits'\'][\''banana'\'][\''value'\']'; // unknown on runtime
eval('new_obj' + array_path + ' = ' + the_value + ';');

Unfortunately after minification the 'new_obj' parameter won't match the new_obj variable. I can't figure out another way to do what I want, because the array_path structure is unknown to me on runtime. Any ideas how I can avoid the eval() function?

Answer Source

If I undertand your question correctly this might be what you are looking for:

var set_value = function(obj, path, value) {
    var limit = path.length;
    // You might want to check if limit is 0 here.
    for (var i = 0; i < limit-1; i++) {
        var key = path[i];
        if (!obj.hasOwnProperty(key)) {
            // Depending on your case you might throw an error
            // here or do something else
            obj[key] = {};
        obj = obj[key];
    obj[path[limit-1]] = value;

And usage:

var new_obj = {},
    array_path = ['foo', 'bar', 'test'],
    the_value = 3;

set_value(new_obj, array_path, the_value);

So all you have to do is convert array_path to a format as above. If you receive it as a string then some regular expressions might be helpful. Although if you have control over the source then just make sure that it is a JSON array.

BTW: Do not use hackish (or any) evals as you did above. Minification is the least of your problems. If you have no control over the source (and it is a good practice to always assume that you don't) then you have a huge security issue at the moment. Someone can inject harmful JavaScript with ease into your code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download