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

查看:66
本文介绍了如何通过 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. And then I want to 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 the index of the object with property name='John' to get the value of the property token.

我该如何解决问题?

推荐答案

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

As the other answers suggest, looping through the array is probably the best way. But I would put it in its 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"的内容,还可以找到包含标记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().

The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().

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

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