查找具有下划线中特定键值的对象的数组索引 [英] find the array index of an object with a specific key value in underscore

查看:127
本文介绍了查找具有下划线中特定键值的对象的数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下划线中,我可以成功找到具有特定键值的项目

In underscore, I can successfully find an item with a specific key value

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }

但我如何找到什么数组索引该对象发生在?

but how do I find what array index that object occurred at?

推荐答案

我不知道是否存在执行此操作的现有下划线方法,但您可以实现与普通javascript相同的结果。

I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript.

Array.prototype.getIndexBy = function (name, value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][name] == value) {
            return i;
        }
    }
    return -1;
}

然后你可以这样做:

var data = tv [tv.getIndexBy(id,2)]

这篇关于查找具有下划线中特定键值的对象的数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆