1

I have a data set as

var data1 = {values:[
  { X: "33", Y: 12 },
  ....
  ]};
var data2 = { values:[
  { X: "Jan", Y: 2 },
  ...
  ]};

I want to load appropriate data set by

$(document).ready(function() {
  $(".test").click(function(){
  var data = $(this).val() // the value will be data1 or data2
           // how can I make the data a JSON equal to data1 or data2 instead of
           // assigning the static value of $(this).val() to it.
  }
});

How can I create the var data from the static value?

1

1 Answer 1

3

Don't.

Have data1, data2 as properties of an object, and use the square bracket member operator to access them.

var dataset = {

    data1: {
        values: [{
            X: "33",
            Y: 12
        }, ....]
    }
    data2: {
        values: [{
            X: "Jan",
            Y: 2
        }, ...]
    };
}

var data = dataset[$(this).val()]

Although if your data1 and data2 are global variables, you could access them the same way from the window object.

var data = window[$(this).val()]

But an object like dataset is still nicer than a bunch of globals.

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

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.