gpt4 book ai didi

javascript - 如何从具有给定(键,值)对的长列表中检索对象?

转载 作者:行者123 更新时间:2023-11-30 05:33:17 24 4
gpt4 key购买 nike

你好有一长串这样的对象:

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(...)

像这样:

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;
});

关于javascript - 如何从具有给定(键,值)对的长列表中检索对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25506438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com