如何将可变字符串插入 JSON 查询?

How to insert a variable string into a JSON query?

我有一个像这样运行良好的查询。它 returns 正确的对象和一切。

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

但是我想做的是做这样的事情。看看我如何使用时间变量并将其插入到 'timeframe' 的查询中?但它总是 returns 未定义。

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
    });

这总是 returns 未定义。我认为这是因为我不能像那样将时间字符串变量插入到查询 JSON 中。我怎样才能插入它以使其格式正确?

试一试:

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
});

或者像这样:

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

甚至这样:

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

因为是异步的。像这样重写

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
    });
    }