1

I want to be able to take JSON into my program and then create objects based off of that data. So, I want to create objects where the name of that object is the value stored in a key value pair. For instance, if I had the following JSON (and I know this isn't perfect JSON):

{
    "objectName" : "**variableName**",
    "someDataName" : "thatData",
    "someOtherDataName" : "thisData"
}

Then I want to be able to make an object like this:

function myObject(thatData, thisData) {
    this.name = name;
    this.thatData = thatData;
}

var **variableName** = new myObject(thatData, thisData);

The key here is that I want to be able to use the value stored in the ObjectName key value pair as the variable name for the object. Is this even possible? I have been looking for how to do this for a while now. I believe that this is different than "Variable" variables in Javascript? because I am trying to use a value in a key value pair to name my objects.

Community
  • 1
  • 1
Nick P
  • 347
  • 1
  • 4
  • 13
  • you can check here http://stackoverflow.com/questions/5187530/variable-variables-in-javascript/37575407#37575407 – A.K. Jun 01 '16 at 17:40
  • I believe that my question is different than the one that you mentioned, as I am trying to use a JSON value in a key/value pair to create my variable name. – Nick P Jun 01 '16 at 17:45
  • 2
    @NickP: Where the value comes from is irrelevant. You want to use the value of a string as variable name. That's all that matters. – Felix Kling Jun 01 '16 at 17:52
  • @NickP I am giving example of key type object – A.K. Jun 02 '16 at 13:24

2 Answers2

2

If I understand correctly what you're trying to do here, one approach may be to set properties within a variable:

let myContainer = {};
// ...
myContainer['whatever_variable_name'] = new ...

You can how use myContainer.whatever_variable_name or myContainer['whatever_variable_name'] to access the new object.

To assign properties from JSON objects, see Object.assign.

NuSkooler
  • 5,391
  • 1
  • 34
  • 58
0

You can use the property accessor on the window object to set the value for a dynamic key on the global scope.

var window["**variableName**"] = new myObject(thatData, thisData);