将string转换为具有相同名称的JSON对象(需要在js中使用某种dynamic代码)

var ObjName = "Person"; //If I assign "Institute" then I need Institute JSON object //I have a global Person JSON with many attributes. var thisObj = ObjName.toObject(); //need something of this kind //I know eval can be used, but just checking any other better way to do this. 

请指教是否有更好的方法将string转换为其在nodejs中的名称的对象,帆js

如果不使用eval,ES5 JavaScript在技术上并不可行。 正如你所知,在这种情况下(或几乎所有)使用eval 并不是一个好主意。 像David所说的另一个select,现在可能是一个很好的select。

 //Set the variable var ObjName = "person"; //define the initial object var thisObj = {}; //Add some objects to it. thisObj[ObjName] = {'things':'stuff'}; //Or, because we know the object name is 'person', attach stuff directly to it. thisObj.person = 'test'; //Or, (again) if we need to reuse the variable as string later on thisObj['person'] = 'test';