我有一个数组:

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

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

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


当前回答

ECMAScript 2015(JavaScript ES6)提供find()数组上的方法:

var myArray=[{id:1,name:“bob”},{id:2,名称:“dan”},{id:3,名称:“barb”},]//抓取与id“2”匹配的Array项var item=myArray.find(item=>item.id===2);//打印console.log(item.name);

它在没有外部库的情况下工作。但是,如果您想要更旧的浏览器支持,您可能需要包含此polyfill。

其他回答

我真的很喜欢Aaron Digulla提供的答案,但需要保留我的对象数组,以便稍后可以迭代。所以我把它改成

var索引器={};对于(var i=0;i<array.length;i++){索引器[array[i].id]=parseInt(i);}//然后可以使用以下命令访问数组中的对象财产数组[索引器[id]].properties

我们可以使用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

如果多次执行此操作,则可以设置映射(ES6):

const map = new Map( myArray.map(el => [el.id, el]) );

然后,您可以简单地执行O(1)查找:

map.get(27).foo

我认为最简单的方法是以下方法,但它在Internet Explorer 8(或更早版本)上不起作用:

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property

使用本机Array.reduce

var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
    return (a.id==id && a) || (b.id == id && b)
});

如果找到,则返回object元素,否则为false