简体   繁体   中英

Better way to get an unique object out of an array

I have an array with objects. Each object got an unique id. What is the best way to get a specific object from the array?

Currently I use something like this

  this.getObjectById = function(objectId){
    return $.grep(this.objects, function(e){ return e.id === objectId; })[0];
  }

but the fact that

$.grep();

returns an array of results I don't know if I should go for this. Because currently I take the first element of this array and it's fine because I just got one element in it.

But is there a more clean way?

Is

Array.prototype.find()

a better one?

Find is faster since it returns the first match, while jquery grep loops trough entire array. If you need full browser support just create you own function:

this.getObjectById = function(objectId){
  for(var i = 0; i<this.objects.length; i++){
    if(objectId == this.objects[i].id) return this.objects[i];
  }
  return null;
}

使用underscore.js _.find()方法来迭代您的集合。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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