I’m currently using javascript eval() to check and create a multidimensional object that I have no idea of the depth.
Basically, I want to know if there’s any way to create this multi-depth object. The object can be as deep as result['one']['two']['three']['four']['five']['six']['seven']. I know there are cases where using eval() is perfectly fine, but I’m also worried about performance. I thought about referencing each depth to a new variable, but I don’t know how to do pointers in Javascript
create = function(fields, create_array){
var field;
for (j = 0; j < len; j++){
field = fields.slice(0, j).join('');
if (field){
// is there any way to do this without eval?
eval('if (typeof result' + field + ' == "undefined" || !result' + field + ') result' + field + ' = ' + (create_array?'[]':'{}') + ';');
}
}
}
Never mind, found my way in. I used a recursive function to ensure that the object was created properly.
being variable “field” a variable outside the function, that contained the levels of the object. doing
result["field"]["name"]["first"] = valuewithout the["field"]or["name"]field existing or defined as an object, would throw an error and stop execution, that’s why I’m pre-creating the object variable, either as an array or object.I couldn’t find another option for the second eval() though. There’s no way to provide a way to access multiple properties on an object without knowing the depth.