I was wondering if this was possible without eval (i hear it's evil).
var myString = 'myObject.property.subproperty';
and convert it to
var obj = {
myObject: {
property: {
subproperty: {}
}
}
};
Been at this for 2 hours.
The val solution that I don't like:
I can do it with input string.
var myString = 'myObject.property.subproperty';
var nameTree = myString.split('.');
var evalString = '';
var myObj = {};
_.forEach(nameTree, function(value, key){
if (key == 0) {
evalString += 'myObj[' + value + '] = {};';
} else {
evalString += '[' + value + '] = {};';
}
});
eval(evalString);
I get:
console.log(myObj);
// {myObject: {property:{subproperty:{}}}};
eval()has to do with your question because you can't even use it to make what you want from your input string. Anyway, here's a working demo: jsfiddle.net/jfriend00/Q9cWa using the same technique hugomg showed (who happens to type faster than I so posted an answer sooner). My version is put into a function.eval().