【问题标题】:How to use a variable for a property name when using underscore.js findWhere function?使用 underscore.js findWhere 函数时如何使用变量作为属性名称?
【发布时间】: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


    【解决方案1】:

    刚刚想通了。 findWhere 的第二个参数是一个对象。所以首先创建对象并将其传递给函数:

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

    有效!

    【讨论】:

    • 是的,但请记住 findWhere 实际上只是伪装的 find 调用,因此为单个值构建 search_obj 对您没有多大作用(或者也许它确实如此)取决于你的口味:)。
    【解决方案2】:

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

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

    如果你真的需要使用findWhere,看看Using a variable for a key in a JavaScript object literal

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2013-11-23
      • 2013-01-07
      • 1970-01-01
      • 2022-01-09
      • 2011-11-30
      • 1970-01-01
      相关资源
      最近更新 更多