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

时间:2015-02-15 19:31:31

标签: javascript json keen-io

我的查询运行得很好。它返回正确的对象和一切。

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

但我想做的是做这样的事情。看看我如何使用时间变量并将其插入“timeframe”的查询中?但是它总是返回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
    });

这总是返回undefined。我认为它是因为我无法将时间字符串变量插入到查询JSON中。如何插入它以使其格式正确?

2 个答案:

答案 0 :(得分:3)

试试这样:

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

答案 1 :(得分:0)

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

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