没有动态的方法在对象字面量中设置对象键。
你所要做的
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"});