Find object by id in an array of JavaScript object

2018-12-30 23:53发布

I've got an array:

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

I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array.

How do I do this in JavaScript or using jQuery?

30条回答
高级女魔头
2楼-- · 2018-12-31 00:00

Another solution is to create a lookup object:

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

... now you can use lookup[id]...

This is especially interesting if you need to do many lookups.

This won't need much more memory since the IDs and objects will be shared.

查看更多
大哥的爱人
3楼-- · 2018-12-31 00:01

I really liked the answer provided by Aaron Digulla but needed to keep my array of objects so I could iterate through it later. So I modified it to

	var indexer = {};
	for (var i = 0; i < array.length; i++) {
	    indexer[array[i].id] = parseInt(i);
	}
	
	//Then you can access object properties in your array using 
	array[indexer[id]].property

查看更多
牵手、夕阳
4楼-- · 2018-12-31 00:01

Shortest,

var theAnswerObj = _.findWhere(array, {id : 42});
查看更多
皆成旧梦
5楼-- · 2018-12-31 00:01

We can use Jquery methods $.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 ); });

use ES6 syntax: Array.find, Array.filter, Array.forEach, Array.map

Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter

查看更多
零度萤火
6楼-- · 2018-12-31 00:04

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

returns the object element if found, otherwise false

查看更多
谁念西风独自凉
7楼-- · 2018-12-31 00:06

I think the easiest way would be the following, but it won't work on Internet Explorer 8 (or earlier):

var result = myArray.filter(function(v) {
    return v.id === '45'; // Filter out the appropriate one
})[0].foo; // Get result and access the foo property
查看更多
登录 后发表回答