jQuery: Index of element in array where predicate

前端 未结 5 520
小鲜肉
小鲜肉 2020-12-20 13:51

I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 14:32

    Use jOrder. http://github.com/danstocker/jorder

    Feed your array into a jOrder table, and add an index on the 'ID' field.

    var table = jOrder(data)
        .index('id', ['ID']);
    

    Then, get the array index of an element by:

    var arrayidx = table.index('id').lookup([{ ID: MyID }]);
    

    If you want the entire row, then:

    var filtered = table.where([{ ID: MyID }]);
    

    Voila.

提交回复
热议问题