使用underscore.js findWhere函数时如何使用变量作为属性名?

Tim*_*ann 5 underscore.js

我在查找如何在使用_.findWhere函数时在underscore.js中动态设置属性时遇到问题.

这是该函数的文档:

findWhere_.findWhere(list, properties) 
Run Code Online (Sandbox Code Playgroud)

查看列表并返回与属性中列出的所有键值对匹配的第一个值.

如果未找到匹配项,或者list为空,则返回undefined.

_.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."}
Run Code Online (Sandbox Code Playgroud)

在文档中建模示例,我想设置属性以动态搜索:

 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"});
Run Code Online (Sandbox Code Playgroud)

结果未定义.

我也尝试过:

_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"});
Run Code Online (Sandbox Code Playgroud)

错误消息是SyntaxError:missing:属性id之后

我怎么能做到这一点?

谢谢你的帮助.

Tim*_*ann 8

刚想通了.findWhere的第二个参数是一个对象.因此,首先创建对象并将其传递给函数:

var myprop = 'newsroom';
var value = 'The New York Times';
var search_obj = {};
search_obj[myprop] = value;

var result =  _.findWhere(publicServicePulitzers,search_obj);
Run Code Online (Sandbox Code Playgroud)

作品!