Find object by id in an array of JavaScript objects

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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?

回答1:

myArray.find(x => x.id === '45').foo; 

From MDN:

The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.


If you want to get an array of matching elements, use the filter() method instead:

myArray.filter(x => x.id === '45'); 

This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:

myArray.filter(x => x.id === '45').map(x => x.foo); 

Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel.



回答2:

As you are already using jQuery, you can use the grep function which is intended for searching an array:

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

The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:

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


回答3:

Another solution is to create a lookup object:

var lookup = {}; for (var i = 0, len = array.length; i 

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.



回答4:

Underscore.js has a nice method for that:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.] obj = _.find(myArray, function(obj) { return obj.id == '45' }) 


回答5:

ECMAScript 2015 provides the find() method on arrays:

var myArray = [  {id:1, name:"bob"},  {id:2, name:"dan"},  {id:3, name:"barb"}, ]  // grab the Array item which matchs the id "2" var item = myArray.find(item => item.id === 2);  // print console.log(item.name);

It works without external libraries. But if you want older browser support you might want to include this polyfill.



回答6:

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 


回答7:

Try the following

function findById(source, id) {   for (var i = 0; i 


回答8:

myArray.filter(function(a){ return a.id == some_id_you_want })[0] 


回答9:

A generic and more flexible version of the findById function above:

// array = [{key:value},{key:value}] function objectFindByKey(array, key, value) {     for (var i = 0; i 


回答10:

You can use filters,

  function getById(id, myArray) {     return myArray.filter(function(obj) {       if(obj.id == id) {         return obj        }     })[0]   }  get_my_obj = getById(73, myArray); 


回答11:

You can get this easily using the map() function:

myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];  var found = $.map(myArray, function(val) {     return val.id == 45 ? val.foo : null; });  //found[0] == "bar"; 

Working example: http://jsfiddle.net/hunter/Pxaua/



回答12:

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



回答13:

While there are many correct answers here, many of them do not address the fact that this is an unnecessarily expensive operation if done more than once. In an extreme case this could be the cause of real performance problems.

In the real world, if you are processing a lot of items and performance is a concern it's much faster to initially build a lookup:

var items = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];  var lookup = items.reduce((o,i)=>o[i.id]=o,{}); 

you can then get at items in fixed time like this :

var bar = o[id]; 

You might also consider using a Map instead of an object as the lookup: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map



回答14:

You may try out Sugarjs from http://sugarjs.com/.

It has a very sweet method on Arrays, .find. So you can find an element like this:

array.find( {id: 75} ); 

You may also pass an object with more properties to it to add another "where-clause".

Note that Sugarjs extends native objects, and some people consider this very evil...



回答15:

Building on the accepted answer:

jQuery:

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

Or CoffeeScript:

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


回答16:

You can do this even in pure JavaScript by using the in built "filter" function for arrays:

Array.prototype.filterObjects = function(key, value) {     return this.filter(function(x) { return x[key] === value; }) } 

So now simply pass "id" in place of key and "45" in place of value, and you will get the full object matching an id of 45. So that would be,

myArr.filterObjects("id", "45"); 


回答17:

Here's how I'd go about it in pure JavaScript, in the most minimal manner I can think of that works in ECMAScript 3 or later. It returns as soon as a match is found.

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' 


回答18:

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 


回答19:

Iterate over any item in the array. For every item you visit, check that item's id. If it's a match, return it.

If you just want teh codez:

function getId(array, id) {     for (var i = 0, len = array.length; i 

And the same thing using ECMAScript 5's Array methods:

function getId(array, id) {     var obj = array.filter(function (val) {         return val.id === id;     });      // Filter returns an array, and we just want the matching item.     return obj[0]; } 


回答20:

Use Array.prototype.filter() function.

DEMO: https://jsfiddle.net/sumitridhal/r0cz0w5o/4/

JSON

var jsonObj =[  {   "name": "Me",   "info": {    "age": "15",    "favColor": "Green",    "pets": true   }  },  {   "name": "Alex",   "info": {    "age": "16",    "favColor": "orange",    "pets": false   }  }, {   "name": "Kyle",   "info": {    "age": "15",    "favColor": "Blue",    "pets": false   }  } ]; 

FILTER

var getPerson = function(name){     return jsonObj.filter(function(obj) {       return obj.name === name;     }); } 


回答21:

If you do this multiple times, you may set up a Map (ES6):

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

Then you can simply do:

map.get(27).foo 


回答22:

Use:

var retObj ={}; $.each(ArrayOfObjects, function (index, obj) {          if (obj.id === '5') { // id.toString() if it is int              retObj = obj;             return false;         }     }); return retObj; 

It should return an object by id.



回答23:

As long as the browser supports ECMA-262, 5th edition (December 2009), this should work, almost one-liner:

var bFound = myArray.some(function (obj) {     return obj.id === 45; }); 


回答24:

This solution may helpful as well:

Array.prototype.grep = function (key, value) {     var that = this, ret = [];     this.forEach(function (elem, index) {         if (elem[key] === value) {             ret.push(that[index]);         }     });     return ret.length 

I made it just like $.grep and if one object is find out, function will return the object, rather than an array.



回答25:

Starting from aggaton's answer, this is a function that actually returns the wanted element (or null if not found), given the array and a callback function that returns a truthy value for the "correct" element:

function findElement(array, callback) {     var elem;     return array.some(function(e) {         if (callback(e)) {             elem = e;             return true;         }     }) ? elem : null; }); 

Just remember that this doesn't natively work on IE8-, as it doesn't support some. A polyfill can be provided, alternatively there's always the classic for loop:

function findElement(array, callback) {     for (var i = 0; i 

It's actually faster and more compact. But if you don't want to reinvent the wheel, I suggest using an utility library like underscore or lodash.



回答26:

Shortest,

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


回答27:

Consider "axesOptions" to be array of objects with an object format being {:field_type => 2, :fields => [1,3,4]}

function getFieldOptions(axesOptions,choice){   var fields=[]   axesOptions.each(function(item){     if(item.field_type == choice)         fields= hashToArray(item.fields)   });   return fields; } 


回答28:

My way to find index of array:

index = myArray.map(getItemId).indexOf(id); getItemId: function(item) {   return item.id; }  // to get foo property use index myArray[index].foo  //If you want to use ES6 index = myArray.map((i) => i.id).indexOf(id) myArray[index].foo 


回答29:

Use the filter method of jQuery:

 $(myArray).filter(function()  {      return this.id == desiredId;  }).first(); 

That will return the first element with the specified Id.

It also has the benefit of a nice C# LINQ looking format.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!