Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

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];
share|improve this question

marked as duplicate by KyleMit, Oriol javascript Jan 12 '15 at 15:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
You need to show the actual JSON data that you're trying to select from in order for us to be able to advise how to access it. – jfriend00 Nov 29 '11 at 5:51
up vote 41 down vote accepted

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;
    }
}
share|improve this answer
3  
This did the trick just had to put [0] at the end to select the first element of the new array that matches the filter. – sergioadh Nov 29 '11 at 14:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.