例如,我有:

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

我怎么解决这个问题?


当前回答

用这个:

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

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

其他回答

用这个:

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

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

一个典型的方法

(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 data=[
      { id_list: 1, name: 'Nick', token: '312312' },
      { id_list: 2, name: 'John', token: '123123' },
    ]

    let resultingToken =  data[_.findKey(data,['name','John'])].token

_。findKey是一个Lodash函数。

var index = Data.findIndex(item => item.name == "John")

这是一个简化版:

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

从mozilla.org:

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

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