简体   繁体   English

如何基于一个属性优化JS对象的数组查找

[英]How to optimize array lookup of JS object based on one property

We have a large array of objects: 我们有很多对象:

var englishStudents = [
    {StudentId: 1, Name: "John"},
    {StudentId: 2, Name: "Jack"},
    {StudentId: 3, Name: "Jane"}
];

Need to check if another similar object is contained in this array, just by comparing one property alone. 仅通过比较一个属性,就需要检查此数组中是否包含另一个相似的对象。

var randomStudent = {StudentId: 1337, Name: "Foo"};

This is what I have, and it seems as though it will work, but I don't think this is the best way to do this. 这就是我所拥有的,并且似乎可以使用,但是我认为这不是最好的方法。

var studentIds = $.map(englishStudents, function (student, index) { return student.StudentId; });
var randomStudentLearnsEnglish = false;
for (var sId in studentIds) {
    if (randomStudent.StudentId == sId) {
        randomStudentLearnsEnglish = true;
        break;
    }
}

What would be the optimized way to do this? 执行此操作的最佳方式是什么?

You should keep student data in a hash table like JHashtable instead of the array. 您应该将学生数据保留在像JHashtable这样的哈希表中,而不是数组中。 For mor complex scenarios, you can maintain more than one hash table, like studentsById , studentsByCountryCode , etc. 对于更复杂的场景,您可以维护多个哈希表,例如studentsByIdstudentsByCountryCode等。

Just do a hash instead of an array, so: 只是做一个哈希而不是一个数组,所以:

var englishStudents = {
    1: {StudentId: 1, Name: "John"},
    2: {StudentId: 2, Name: "Jack"},
    3: {StudentId: 3, Name: "Jane"}
};

and then to retrieve, simply do: 然后进行检索,只需执行以下操作:

var student = englishStudents[id];

If you really want, you can create a further indexing scheme: 如果确实需要,可以创建其他索引方案:

var englishStudents = [
    {StudentId: 1, Name: "John"},
    {StudentId: 2, Name: "Jack"},
    {StudentId: 3, Name: "Jane"}
];
 //if doing this a lot of time, take the one time hit of construction and memory
var idToNameMap = createIdToNameMap(englishStudents); //returns {'1': 'John', '2': Jack' , '3': 'Jane'}

var randomStudent = getRandomStudent();
if( idToNameMap[ randomStudent.StudentId] != undefined){ ... }

If all you want to know is if the ID exists can do this: 如果您只想知道ID是否存在,可以执行以下操作:

function checkIdExists( id){
    /* map array of matching ID, if none exists length of array is zero*/
    return  $.map(englishStudents, function (student, index) { 
               return student.StudentId==id; 
    }).get().length;
});

Use: 采用:

 if( checkIdExists( 1234)){
     /* run exists code*/
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM