例如,我有:

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

我怎么解决这个问题?


当前回答

可以使用过滤法

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

其他回答

因为排序部分已经回答了。我将提出另一种优雅的方法来获取数组中属性的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');

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

const index = Data.findIndex(item => item.name === '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

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

与德国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);