BigBoy1337
BigBoy1337

Reputation: 4963

How to insert a variable string into a JSON query?

I have a query that runs just fine like this. It returns the right object and everything.

    var all = new Keen.Query("extraction", {
      eventCollection: "android-sample-button-clicks",
      timeframe: 'previous_300_minutes'
    });

But what I want to do is to do something like this. See how I use the time variable and insert it into the query for 'timeframe'? But then it always returns undefined.

if (this.value == "1"){
      var time = 'previous_300_minutes'
    } else {
      var time = 'previous_30_minutes'
    }
    var all = new Keen.Query("extraction", {
      eventCollection: "android-sample-button-clicks",
      timeframe: time
    });

This always returns undefined. I figure its because I cannot insert the time string variable into the query JSON like that. How can I insert this so that it is formatted correctly?

Upvotes: 1

Views: 226

Answers (2)

arkascha
arkascha

Reputation: 42915

Have a try like this:

var time;
if (this.value == "1"){
  time = 'previous_300_minutes'
} else {
  time = 'previous_30_minutes'
}
var all = new Keen.Query("extraction", {
  eventCollection: "android-sample-button-clicks",
  timeframe: time
});

Or like this:

var time = (this.value == "1") ? 'previous_300_minutes' : 'previous_30_minutes';
var all = new Keen.Query("extraction", {
  eventCollection: "android-sample-button-clicks",
  timeframe: time
});

Or even like that:

var all = new Keen.Query("extraction", {
  eventCollection: "android-sample-button-clicks",
  timeframe: (this.value == "1") ? 'previous_300_minutes' : 'previous_30_minutes'
});

Upvotes: 3

itzMEonTV
itzMEonTV

Reputation: 20339

Since it is asynchronous. rewrite like this

if (this.value == "1"){
      var time = 'previous_300_minutes'
    var all = new Keen.Query("extraction", {
    eventCollection: "android-sample-button-clicks",
    timeframe: time
    });
   } else {
      var time = 'previous_30_minutes'
    var all = new Keen.Query("extraction", {
    eventCollection: "android-sample-button-clicks",
    timeframe: time
    });
    }

Upvotes: 0

Related Questions