使用 underscore.js findWhere 函数时如何为属性名称使用变量? [英] How to use a variable for a property name when using underscore.js findWhere function?
问题描述
我在使用 _.findWhere 函数时无法弄清楚如何在 underscore.js 中动态设置属性.
这是该函数的文档:
<块引用>findWhere_.findWhere(list, properties)
查看列表并返回匹配所有列表的第一个值属性中列出的键值对.
如果没有找到匹配项,或者列表为空,则返回 undefined.
_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"});=>{年份:1918,新闻编辑部:纽约时报",理由:因为它为公众服务,完整地发布了这么多官方报告,欧洲政治家关于进步和发展的文件和演讲战争的进行."}
建模文档中的例子,我想设置属性来动态搜索:
var publicServicePulitzers = [{"newsroom":"The New York Times", "year":2013 },{"newsroom":"The Los Angeles Times", "year":2012 }];var myprop = '新闻室';_.findWhere(publicServicePulitzers, { myprop : "纽约时报"});
结果未定义.
我也试过:
_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"});
错误信息是 SyntaxError: missing : after property id
我怎样才能做到这一点?
感谢您的帮助.
刚刚想通了.findWhere 的第二个参数是一个对象.所以首先创建对象并将其传递给函数:
var myprop = 'newsroom';var value = '纽约时报';var search_obj = {};search_obj[myprop] = 值;var 结果 = _.findWhere(publicServicePulitzers,search_obj);
有效!
I'm having trouble figuring out how to set a property dynamically in underscore.js while using the _.findWhere function.
Here's the documentation for the function:
findWhere_.findWhere(list, properties)
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.
If no match is found, or if list is empty, undefined will be returned.
_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"}); => {year: 1918, newsroom: "The New York Times", reason: "For its public service in publishing in full so many official reports, documents and speeches by European statesmen relating to the progress and conduct of the war."}
Modeling the example in the docs, I want to set the property to search for dynamically:
var publicServicePulitzers = [
{"newsroom":"The New York Times", "year":2013 },
{"newsroom":"The Los Angeles Times", "year":2012 }
];
var myprop = 'newsroom';
_.findWhere(publicServicePulitzers, { myprop : "The New York Times"});
The result is undefined.
I also tried:
_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"});
The error message is SyntaxError: missing : after property id
How can I accomplish this?
Thanks for any help.
Just figured it out. The second parameter to findWhere is an object. So create the object first and pass that to the function:
var myprop = 'newsroom';
var value = 'The New York Times';
var search_obj = {};
search_obj[myprop] = value;
var result = _.findWhere(publicServicePulitzers,search_obj);
Works!
这篇关于使用 underscore.js findWhere 函数时如何为属性名称使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!