例如,我有:

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

我怎么解决这个问题?


当前回答

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

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

其他回答

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

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

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

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

可以使用过滤法

 const filteredData = data.filter(e => e.name !== 'john');
var index = Data.findIndex(item => item.name == "John")

这是一个简化版:

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

从mozilla.org:

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

一个典型的方法

(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.