【发布时间】: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