Is it possible to create an object dynamically in JS without using Eval?

Asked

Viewed 4,208 times

3

I have the following code:

Arr = ["meu", "objeto", "dinamico"];
Val = 100;
Eval = "";
obj = {};
for(i in Arr){
    Eval += "['"+ Arr[i] + "']";
    eval("obj"+Eval+"={}")
}
eval("obj"+Eval+"="+Val);

As you can see, this code dynamically generates the property obj.meu.objeto.dinamico and adds the value of Val in it, but this code is a bit ridiculous, I tried to make the same code without using eval(), but I can’t imagine a decent solution.

  • I recommend you use the traditional loop for(i=0;...) or foreach method to iterate on vectors. for-in does not guarantee that indexes are accessed in ascending order and can also iterate over non-numeric fields (if someone says monkeypatching in Object.prototype or Array.)

3 answers

5


Your Eval code is already using the trick you need to no longer use Eval: Access properties via string:

//Em Javascript esses dois são equivalentes:
obj.foo = 17
obj['foo'] = 17

Already to make your dynamic object I find it easier to build from "bottom up":

function make_object_path(path, value){
    var curr = value;
    for(var i=path.length-1; i >= 0; i--){
       var o = {};
        o[path[i]] = curr;
        curr = o;
    }
    return curr;
}
    
var obj = make_object_path(["meu", "objeto", "dinamico"], 100);
alert(obj.meu.objeto.dinamico);

2

It’s very simple. An object in javascript can be used as an array, i.e.:

var arr = ["meu", "objeto", "dinamico"];
var val = 100;
var obj = {};
var currentObj = obj;
var lastIndex = arr.length - 1;

for (i in arr) {
    currentObj[arr[i]] =  (i == lastIndex) ? val : {} ;
    currentObj = currentObj[arr[i]];
}

console.log(obj);

The condition i == lastIndex serves to check if it is in the last index of the array to set the desired value, in case 100. The variable currentObj serves to modify the object obj from the last created index. This is possible because by passing an object to a variable js saves a reference to the original object, that is, when modifying the object currentObj we will also be modifying the object obj.

0

The solution I had found is as follows:

function createDynamicObject(val, arr, obj){
    //
    if(typeof obj == "undefined")
        obj = {};

    //
    if(arr.length > 1){
        key = arr.shift();
        obj[ key ] = {};
        createDynamicObject(val, arr, obj[ key ]);
    }else{
        key = arr.shift();
        obj[ key ] = val;
    }

    //
    return obj;
} 

//
meuObjeto = createDynamicObject(100, ["minha", "propriedade", "dinamica"]);
console.log(meuObjeto.minha.propriedade.dinamica);

but what @hugomg answered is very interesting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.