Javascript 如何将字符串转换为对象类型
我使用emberjs查找内容,但问题与JS的关系比Ember更大 我有两个变量:Javascript 如何将字符串转换为对象类型,javascript,ember.js,Javascript,Ember.js,我使用emberjs查找内容,但问题与JS的关系比Ember更大 我有两个变量:var type=“stars”;var term=“5” 我的API中有一个名为stars的属性 当我这样做时:App.Response.find({stars:term})我找到结果 但是,当我这样做时:App.Response.find({type:term})I不查找结果。我想把它翻译成App.Response.find({stars:term}),因为type有值“stars” 我假设这是因为type(带值
var type=“stars”;var term=“5”
我的API中有一个名为stars的属性
当我这样做时:App.Response.find({stars:term})代码>我找到结果
但是,当我这样做时:App.Response.find({type:term})代码>I不查找结果。我想把它翻译成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);
准确-它不会计算对象关键点。如果要将该对象动态创建为{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;
};
在对象文本中没有设置对象关键点的动态方法
你必须这样做
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({type:5})
.hmm我如何修复它,使App.Response.find({type:term})
与App.Response.find({stars:term})
既然type=“stars”@Anthony看到我下面的答案,我相信它应该能解决你的问题。这基本上是App.Response.find({type:5})
.hmm我如何修复它,使App.Response.find({type:term})
与App.Response.find({stars:term})
既然type=“stars”@Anthony看到我下面的答案,我相信它应该能解决你的问题