1
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.

Please advise if there is better way to convert String to Object of its name in nodejs, sails js

1
  • Would it be a working alternative for you to use a property of a (e.g.) global object with that name? If so, you could write: myGlobalObj[ObjName] = {}; where ObjName still contains "Person" or "Institute" and access is done like myGlobalObj["Person"]. Commented Jul 5, 2015 at 17:57

2 Answers 2

1

It is not technically possible in ES5 JavaScript to do exactly what you want without the use of eval. As you have eluded to, it would not be a good idea to use eval in the this situation (or pretty much all). An alternative such as that which David suggested is probably a good go-to for now.

Sign up to request clarification or add additional context in comments.

Comments

1
//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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.