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];
Since you already have jQuery, you could use
$.grep:So something like this:
that will leave you with an array of matching entries from
ObjectsListin the arraymatches. The above assumes thatObjectsListhas a structure like this:If you know that there is only one match or if you only want the first then you could do it this way:
There are a lot of variations on the
forloop approach and a lot of people will wag a finger at me because they thinkcontinueis a bad word; if you don’t likecontinuethen you could do it this way: