【问题标题】:How to retrieve an object from a long list having a given (key,value) pair?如何从具有给定(键,值)对的长列表中检索对象?
【发布时间】:2014-08-26 12:58:32
【问题描述】:

您好,有一长串类似的对象:

var myLongList = [
{id="1", desc:"ahahah"},
{id="2", desc:"ihihih"},
{id="3", desc:"ohohoh"},
...
{id="N", desc:"olala"}
]

我需要使用id="14575" 检索对象。由于我的列表很长,而且我必须进行很多这样的检索,所以我不想循环遍历列表来获取我的对象。

到目前为止,我使用一个函数从列索引我的数组:

function index(js, indexColumn){
    var out={};
    var o;
    for (var key in js) {
        o = js[key];
        out[o[indexColumn]]=o;
    }
    return out;
}

var myLongListIndexed = index(myLongList, "id"); 的调用会构建一个索引列表,myLongListIndexed["14575"] 返回我心爱的对象。

有没有更标准的方法来根据(键,值)对从列表中检索对象?

【问题讨论】:

  • 听起来几乎是最明智的做法,但将for..in 与数组一起使用并不是一个好主意。最好使用常规的for 循环或js.forEach(...)

标签: javascript list indexing


【解决方案1】:

听起来几乎是最明智的做法,但将for..in 与数组一起使用并不是一个好主意。最好使用常规的for 循环或js.forEach(...)

像这样:

for (var i = 0; i < js.length; i += 1) {
    o = js[i];
    out[o[indexColumn]]=o;
}

或者这个(需要 ES5):

js.forEach(function(el) {
    out[el[indexColumn]] = el;
});

jQuery 版本(不需要 ES5):

$.each(js, function() {
    out[this[indexColumn]] = this;
});

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2013-10-28
    • 2021-01-29
    • 1970-01-01
    • 2022-01-06
    • 2012-06-05
    • 2021-09-02
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多