【发布时间】:2014-02-07 15:07:35
【问题描述】:
在下划线中,我可以成功找到具有特定键值的项目
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }
但是我如何找到该对象出现在哪个数组索引处?
【问题讨论】:
-
谢谢 - 这很有用 - 但在列出的示例中,您正在数字数组中搜索单个数字 - 我正在寻找对象数组中的键值。这个函数能适应吗?
-
无论是数字测试还是您的属性等式谓词都没有关系,是的。
-
试试
findIndex:var dataIndex = _.findIndex(tv, { id: voteID }) -
请考虑接受the answer that gives an Underscore solution,按照问题的要求。