例如,我有:

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

然后,我想按名称(例如)对该对象进行排序/反转。然后我想要得到这样的东西:

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

现在我想知道对象的索引属性名称='John',以获得属性令牌的值。

我怎么解决这个问题?


当前回答

正如其他答案所表明的那样,遍历数组可能是最好的方法。但我会把它放在自己的函数里,让它更抽象一点:

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':

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

该函数在未找到时返回-1,因此它遵循与Array.prototype.indexOf()相同的构造。

其他回答

我所知道的唯一方法是遍历所有数组:

var index = -1;
for(var i=0; i<Data.length; i++)
  if(Data[i].name === "John") {
    index = i;
    break;
  }

或不区分大小写:

var index = -1;
for(var i=0; i<Data.length; i++)
  if(Data[i].name.toLowerCase() === "john") {
    index = i;
    break;
  }

结果变量index包含对象的索引,如果没有找到,则为-1。

collection.findIndex(item => item.value === 'smth') !== -1

你可以在Lodash库中使用findIndex。

例子:

var users = [
{ 'user': 'barney',  'active': false },
{ 'user': 'fred',    'active': false },
{ 'user': 'pebbles', 'active': true }
            ];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0

// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2
var index = Data.findIndex(item => item.name == "John")

这是一个简化版:

var index = Data.findIndex(function(item){ return item.name == "John"})

从mozilla.org:

findIndex()方法返回数组中满足所提供测试函数的第一个元素的索引。否则返回-1。

你可以使用数组。使用自定义函数作为参数进行排序,以定义排序机制。

在你的例子中,它会给出:

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

Data.sort(function(a, b){
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});

alert("First name is : " + Data[0].name); // alerts 'John'
alert("Second name is : " + Data[1].name); // alerts 'Nick'

如果a应该在b之前,排序函数必须返回-1;如果a应该在b之后,则返回1;如果两者相等,则返回0。由您在排序函数中定义正确的逻辑对数组进行排序。

错过了你问题的最后一部分,你想知道索引。就像其他人说的那样,你必须循环遍历数组才能找到它。