例如,我有:

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

我怎么解决这个问题?


当前回答

也许是物体。钥匙,对象。条目和对象。Values方法可能会有所帮助。

其他回答

var fields = {
  teste:
  {
    Acess:
    {
      Edit: true,
      View: false
    }
  },
  teste1:
  {
    Acess:
    {
      Edit: false,
      View: false
    }
  }
};

console.log(find(fields,'teste'));

function find(fields,field) {
  for(key in fields) {
    if(key == field) {
      return true;
    }
  }
  return false;
}

如果你有一个对象,里面有多个对象,如果你想知道某个对象是否包含在主对象中,只需使用find(MasterObject, 'Object to Search')。该函数将返回是否存在(TRUE或FALSE)的响应。我希望在这方面有所帮助——可以在JSFiddle上看到这个例子。

这可能很有用:

function showProps(obj, objName) {
  var result = "";
  for (var i in obj)
    result += objName + "." + i + " = " + obj[i] + "\n";
  return result;
}

我从“处理对象”中复制了这个。

使用Underscore.js:

var index = _.indexOf(_.pluck(item , 'name'), 'Nick');
var index = Data.findIndex(item => item.name == "John")

这是一个简化版:

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

从mozilla.org:

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

可以使用过滤法

 const filteredData = data.filter(e => e.name !== 'john');