如何在JavaScript中通过其属性获取对象的索引? [英] How to get index of object by its property in JavaScript?

查看:111
本文介绍了如何在JavaScript中通过其属性获取对象的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有:

var Data = [
  { id_list: 1, name: 'Nick', token: '312312' },
  { id_list: 2, name: 'John', token: '123123' },
]

然后我想通过 name 排序/反向此对象。我得到这样的东西:

Then i want to sort/reverse this object by name, for example. I get something like this:

var Data = [
  { id_list: 2, name: 'John', token: '123123' },
  { id_list: 1, name: 'Nick', token: '312312' },
]

现在我想知道具有属性 name ='John'的对象索引,以获取属性令牌的值。

And now i want to know index of object with property name='John' to get value of property token.

推荐答案

正如其他答案所示,循环遍历数组可能是最好的方法。但我会把它放在它自己的函数中,并使它更抽象一点:

As the other answers suggest, looping through the array is probably the best way. But I would put it in it's own function, and make it a little more abstract:

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

var Data = [
    {id_list: 2, name: 'John', token: '123123'},
    {id_list: 1, name: 'Nick', token: '312312'}
];

有了这个,您不仅可以找到哪个包含'John',而且您可以找到包含token'312312':

With this, not only can you find which one contains 'John' but you can find which contains the token '312312':

findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1

编辑:
更新后的功能未找到时返回-1,因此它遵循与相同的结构Array.prototype.indexOf()

这篇关于如何在JavaScript中通过其属性获取对象的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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