例如,我有:

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',以获得属性令牌的值。

我怎么解决这个问题?


当前回答

你可以在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

其他回答

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

如果你在Internet Explorer上有问题,你可以使用map()函数,它从9.0开始支持:

var index = Data.map(item => item.name).indexOf("Nick");

一个典型的方法

(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.
let indexOf = -1;
let theProperty = "value"
let searchFor = "something";

theArray.every(function (element, index) {

    if (element[theProperty] === searchFor) {
        indexOf = index;
        return false;
    }
    return true;
});

因为排序部分已经回答了。我将提出另一种优雅的方法来获取数组中属性的indexOf

你的例子是:

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

你可以:

var index = Data.map(function(e) { return e.name; }).indexOf('Nick');

var数据= [{ id_list: 1、 名称:“尼克”, 令牌:“312312” }, { id_list: 2 名称:“约翰”, 令牌:“123123” } ] var index = Data.map(函数(e) { 返回e.name; }) .indexOf(“尼克”); console.log(索引)

Array.prototype.map在Internet Explorer 7或Internet Explorer 8上不可用。ES5的兼容性

这里是ES6和箭头语法,这更简单:

const index = Data.map(e => e.name).indexOf('Nick');