簡體   English   中英

如何將String轉換為對象類型

[英]How to convert String to an object type

我正在使用emberjs查找內容,但問題是與Ember相比,與JS相關的更多。

我有兩個變量: var type = "stars"; var term = "5" var type = "stars"; var term = "5"

我的API中有一個稱為星號的屬性。

當我這樣做時: App.Response.find({stars: term}); 我找到結果

但是,當我這樣做時: App.Response.find({type: term}); 沒有找到結果。 我希望將其翻譯為App.Response.find({stars: term})因為type值為"stars"

我假設這是因為type (帶有值stars )不被理解為哈希鍵?

確實-它不會評估對象鍵。 如果要動態創建為{stars:5}對象,則可以執行以下操作:

var obj = {};
obj[type] = term;//Using the array notation will cause JS to evaluate type to "stars" and use that as the key
//obj is now {stars:5}
App.Response.find(obj);

沒有動態方法可以在對象文字中設置對象鍵。

你必須做

var conditions = {},
    type       = "stars",
    term       = "5";

conditions[type] = term;
App.Response.find(conditions);

如果您發現自己經常使用此模式,則可以設置類似

var buildObject = function(key, value) {
  var base = {},
      base[key] = value;
  return base;
};

var type = "stars",
    term = "5";

App.Response.find(buildObject(type, term));

// or directly as
App.Response.find(buildObject("stars", "5"));

最后,讓我們的buildObject助手更加有用

// accepts [key, value] pairs
var buildObject = function() {
  var base = {};
  for (var i=0; i<arguments.length; i++) {
    base[arguments[i][0]] = arguments[i][1];
  };
  return base;
};

現在我們可以多對傳遞

App.Response.find(buildObject(["stars", "5"], ["foo", "bar"]));

// equivalent to
App.Response.find({stars: "5", foo: "bar"});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM