按属性值获取数组中的下一个对象

Get next object in an array by property value?

本文关键字:一个对象 数组 属性 获取      更新时间:2023-09-26

Background

我定义和设置了一个对象数组(用户),如下所示:

// object definition
function Users()
{
  this.Id = null;
  this.Name = null;
  this.FirstName = null;
  this.LastName = null;
  this.IsActive = null;
  this.Title = null;
  this.index = null;
  this.selected = null;
}
// object array
var AllUsers = [];
// ...
// an ajax call retrieves the Users and adds them to the AllUsers array
// ...

索引值在每个用户上设置为检索它们的顺序。检索用户后,可以逐个选择用户,并将其从列表移动到页面上的表。选择后,对于数组中的选定对象,selected 属性将设置为 true。

我正在使用 grep 返回所有选定的用户。

var SelectedUsers = $.grep(AllUsers,function(obj){
  return obj["selected"] == true;
});

下面是返回的数据示例:

[ 
  Object { 
    Id="00540000001AbCdEFG", 
    Name="First Last1", 
    FirstName="First", 
    LastName="Last1", 
    Title="Title", 
    index=56, 
    selected=true 
  },
  Object { 
    Id="00540000001AbChIJK", 
    Name="First Last2", 
    FirstName="First", 
    LastName="Last2", 
    Title="Title", 
    index=12, 
    selected=true 
  },
  Object { 
    Id="00540000001AbClMNO", 
    Name="First Last3", 
    FirstName="First", 
    LastName="Last3", 
    Title="Title", 
    index=92, 
    selected=true 
  }
]

问题

我希望能够对数据进行分页,为此,我需要能够按索引获取下一个和上一个选定的用户。我该怎么做?

例如,如果我在表中打开第一个选定用户 (index=56),如何获取具有下一个索引的用户(第三个选定用户,索引=92)?

JSFiddle

小提琴:http://jsfiddle.net/iambriansreed/KEXwM/

JavaScript 新增:

SelectedUsers.sort(function(a,b){
      return a.index == b.index ? 0 : (a.index < b.index ? -1 : 1)});

如果您不想修改原始SelectedUsers数组,请将排序定义为新变量:

var SortedSelectedUsers = SelectedUsers.slice(0);
SortedSelectedUsers.sort(function(a,b){
      return a.index == b.index ? 0 : (a.index < b.index ? -1 : 1)});

为什么不按索引对数组进行排序?

allUsers.sort(function(a, b) {
    return(a.index - b.index);
});

然后,下一个选定的用户将是所选数组中的下一个用户。 您可以沿着阵列向上走,直到找到选定的用户。

或者,您可以使用 grep 函数获取所有选定的用户,然后按索引对其进行排序,这样下一个选定的用户将只是 selectedUsers 数组中的下一个用户,如下所示:

var SelectedUsers = j$.grep(AllUsers,function(obj){
  return obj["selected"] == true;
}).sort(function(a, b) {
    return(a.index - b.index);
});

按索引实现自己的排序函数:

function compareUsers(a,b)
{
    return (a.index - b.index);
}

并对对象进行排序:

SelectedUsers.sort(compareUsers);

现在,所有索引都按正确的顺序排列。由此,很容易按索引号获取以下或前面的对象。