gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:09:56 28 4
gpt4 key购买 nike

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

这是该函数的文档:

findWhere_.findWhere(list, properties) 

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.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

我怎样才能做到这一点?

谢谢你的帮助。

最佳答案

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

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

var result = _.findWhere(publicServicePulitzers,search_obj);

作品!

关于underscore.js - 使用 underscore.js findWhere 函数时如何为属性名称使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21009572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com