【发布时间】:2014-01-09 00:37:24
【问题描述】:
在使用 _.findWhere 函数时,我无法弄清楚如何在 underscore.js 中动态设置属性。
这是函数的文档:
findWhere_.findWhere(list, properties)遍历列表并返回第一个匹配所有 属性中列出的键值对。
如果没有找到匹配项,或者列表为空,则返回 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."}
对文档中的示例进行建模,我想将属性设置为动态搜索:
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"});
结果未定义。
我也试过了:
_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"});
错误信息是 SyntaxError: missing : after property id
我怎样才能做到这一点?
感谢您的帮助。
【问题讨论】:
标签: underscore.js