我有一个数组:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]

我无法更改阵列的结构。我收到了一个45的id,我想得到数组中该对象的“bar”。

如何在JavaScript或使用jQuery实现这一点?


当前回答

最近,我不得不面对同样的事情,我需要从一个巨大的数组中搜索字符串。

经过一番搜索,我发现用简单的代码就能轻松处理:

代码:

var items = mydata.filter(function(item){
    return item.word.toLowerCase().startsWith( 'gk );
})

看见https://jsfiddle.net/maheshwaghmare/cfx3p40v/4/

其他回答

最短,

var theAnswerObj = _.findWhere(array, {id : 42});

由于您已经在使用jQuery,因此可以使用grep函数来搜索数组:

var result = $.grep(myArray, function(e){ return e.id == id; });

结果是找到项的数组。如果您知道对象始终存在,并且它只出现一次,那么只需使用result[0].foo获取值。否则,应检查结果数组的长度。例子:

if (result.length === 0) {
  // no result found
} else if (result.length === 1) {
  // property found, access the foo property using result[0].foo
} else {
  // multiple items found
}

查找数组索引的方法:

index = myArray.map((i) => i.id).indexOf(value_of_id);
item = myArray[index];

下面的代码将帮助您从数据中的嵌套对象中搜索值。

const updatedData = myArrayOfObjects.filter((obj: any) => Object.values(obj).some((val: any) => {
   if (typeof (val) == typeof ("str")) {
      return val.toString().includes(Search)
   } else {
      return Object.values(val).some((newval: any) => {
         if (newval !== null) {
            return newval.toString().includes(Search)
         }
      })
   }
}))

动态缓存查找

在这个解决方案中,当我们搜索某个对象时,我们将其保存在缓存中。这是“始终搜索解决方案”和“为预先计算的每个对象创建哈希图”之间的中间点。

让cachedFind=(()=>{let cache=new Map();return(arr,id,el=null)=>cache.get(id)||(el=arr.find(o=>o.id==id),cache.set(id,el),el);})();// ---------//测试// ---------let myArray=[…Array(100000)].map((x,i)=>({‘id‘:‘${i}‘,‘foo‘:‘bar_${i}‘}));//示例用法console.log(cachedFind(myArray,'1234').foo);//基准让板凳=(id)=>{console.time('time for'+id);console.log(cachedFind(myArray,id).foo);//查找console.timeEnd('time for'+id);}console.log('-----无缓存-----');工作台(50000);工作台(79980);工作台(99990);console.log('-----缓存-----');工作台(79980);//高速缓存的工作台(99990);//高速缓存的