如何在使用下划线时将变量用作属性名称.js findWhere 函数



在使用 _.findWhere 函数时,我无法弄清楚如何在下划线中动态设置属性.js。

以下是该函数的文档:

findWhere_.findWhere(list, properties) 

查看列表并返回与所有 属性中列出的键值对。

如果未找到匹配项,或者列表为空,则将返回未定义。

_.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"});

错误消息是语法错误:缺少:在属性 ID 之后

我怎样才能做到这一点?

感谢您的任何帮助。

刚想通。 要查找的第二个参数在哪里是一个对象。因此,首先创建对象并将其传递给函数:

var myprop = 'newsroom';
var value = 'The New York Times';
var search_obj = {};
search_obj[myprop] = value;
var result =  _.findWhere(publicServicePulitzers,search_obj);

工程!

不要为此使用 findWhere,而是使用更通用的find

_.find(publicServicePulitzers, function(prize) {
    return price[myprop] == "The New York Times";
});

如果你真的需要使用findWhere,请查看在 JavaScript 对象文字中使用变量作为键。

相关内容

最新更新