我有一个数组:

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

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

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


当前回答

基于公认的答案:

jQuery:

var foo = $.grep(myArray, function(e){ return e.id === foo_id})
myArray.pop(foo)

或CoffeeScript:

foo = $.grep myArray, (e) -> e.id == foo_id
myArray.pop foo

其他回答

以下是我将如何在纯JavaScript中实现它,以我所能想到的在ECMAScript 3或更高版本中工作的最简单的方式。一旦找到匹配项,它就会返回。

var getKeyValueById = function(array, key, id) {
    var testArray = array.slice(), test;
    while(test = testArray.pop()) {
        if (test.id === id) {
            return test[key];
        }
    }
    // return undefined if no matching id is found in array
    return;
}

var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');

// result is 'bar', obtained from object with id of '45'

动态缓存查找

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

让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);//高速缓存的

尝试以下操作

function findById(source, id) {
  for (var i = 0; i < source.length; i++) {
    if (source[i].id === id) {
      return source[i];
    }
  }
  throw "Couldn't find object with id: " + id;
}

你可以试试Sugarjshttp://sugarjs.com/.

它在Arrays上有一个非常好的方法,.find。所以你可以找到这样的元素:

array.find( {id: 75} );

您还可以向其传递具有更多财产的对象,以添加另一个“where-clause”。

请注意,Sugarjs扩展了本地对象,有些人认为这非常邪恶。。。

我们可以使用Jquery方法$.each()/$.grep()

var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}

or

var data = $.grep(array, function( n, i ) {
  return ( n !== 5 && i > 4 );
});

使用ES6语法:

Array.find, Array.filter, Array.forEach, Array.map

或使用Lodashhttps://lodash.com/docs/4.17.10#filter强调https://underscorejs.org/#filter