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

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 obj.meu.objeto.dinamico property and adds the value of Val to it, however this code is somewhat ridiculous, I tried to make the same code without using eval() , but I can not imagine a decent solution.

    
asked by anonymous 15.05.2015 / 14:45

3 answers

4

Your code with eval is already using the trick you need to no longer use eval: Property access via string:

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

Now to make your dynamic object easier to build from the 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);
    
15.05.2015 / 15:03
2

It's quite simple. An object in javascript can be used as an array, that is:

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 i == lastIndex condition is to check if it is in the last array index to set the desired value, in the 100 case. The currentObj variable is used to modify the obj object from the last created index. This is possible because passing an object to a variable js saves a reference to the original object, that is, when we modify the object currentObj we are also modifying the object obj .

    
15.05.2015 / 15:03
0

The solution I found was the following:

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 replied is very interesting.

    
15.05.2015 / 15:18