我在查找如何在使用_.findWhere函数时在underscore.js中动态设置属性时遇到问题.
这是该函数的文档:
Run Code Online (Sandbox Code Playgroud)findWhere_.findWhere(list, properties)查看列表并返回与属性中列出的所有键值对匹配的第一个值.
如果未找到匹配项,或者list为空,则返回undefined.
Run Code Online (Sandbox Code Playgroud)_.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."}
在文档中建模示例,我想设置属性以动态搜索:
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之后
我怎么能做到这一点?
谢谢你的帮助.
刚想通了.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)
作品!