Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from array of objects based on property value in JavaScript [duplicate]

I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.

Suppose an object has id and name, how do I select them from my array variable?

var ObjectsList = data; var id = $("#DropDownList > option:selected").attr("value"); ObjectsList["id=" + id]; 
like image 390
sergioadh Avatar asked Nov 29 '11 05:11

sergioadh


People also ask

How do you get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.

How do you check if an array of objects has duplicate values in JavaScript?

To check if the array of objects have duplicate property values with JavaScript, we can use the JavaScript array's map and some method to map the array to the property values we want to check.


1 Answers

Since you already have jQuery, you could use $.grep:

Finds the elements of an array which satisfy a filter function. The original array is not affected.

So something like this:

var matches = $.grep(ObjectsList, function(e) { return e.id == id }); 

that will leave you with an array of matching entries from ObjectsList in the array matches. The above assumes that ObjectsList has a structure like this:

[     { id: ... },     { id: ... },     ... ] 

If you know that there is only one match or if you only want the first then you could do it this way:

for(var i = 0, m = null; i < ObjectsList.length; ++i) {     if(ObjectsList[i].id != wanted_id)         continue;     m = a[i];     break; } // m is now either null or the one you want 

There are a lot of variations on the for loop approach and a lot of people will wag a finger at me because they think continue is a bad word; if you don't like continue then you could do it this way:

for(var i = 0, m = null; i < ObjectsList.length; ++i) {     if(ObjectsList[i].id == wanted_id) {         m = ObjectsList[i];         break;     } } 
like image 74
mu is too short Avatar answered Sep 20 '22 17:09

mu is too short