例如,我有:

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(){
  if (!Array.prototype.indexOfPropertyValue){
       Array.prototype.indexOfPropertyValue = function(prop, value){
      for (var index = 0; index < this.length; index++){
        if (this[index][prop]){
          if (this[index][prop] == value){
            return index;
          }
        }
       }
      return -1;
    }
  }
 })();

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

 Data.indexOfPropertyValue('name', 'John'); // Returns 1 (index of array);
 Data.indexOfPropertyValue('name', 'Invalid name') // Returns -1 (no result);
 var indexOfArray = Data.indexOfPropertyValue('name', 'John');
 Data[indexOfArray] // Returns the desired object.

其他回答

与德国Attanasio Ruiz的答案不同,您可以使用Array.reduce()而不是Array.map()来消除第二个循环;

var Data = [
    { name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
    return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -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

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

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()相同的构造。

用这个:

Data.indexOf(_.find(Data, function(element) {
  return element.name === 'John';
}));

它假设您正在使用Lodash或Underscore.js。

如果你喜欢使用ES6,数组现在有了findIndex函数。这意味着你可以这样做:

const index = Data.findIndex(item => item.name === 'John');