lilymz
lilymz

Reputation: 387

How to get the key value of a JSON object matching another given value?

i have this JSON:

var projects_array = new Array(
{name:"myName1", id:"myid1", index:1},
{name:"myName2", id:"myid2", index:2},
{name:"myName3", id:"myid3", index:3},  

);

I need to get the "index" value of the object matching an specific "id" value. So if my "id" is "myid1" y would get "1".

here is part of my code:

 var myid = $(this).attr('id'); //this is the id value

projects_array.map(function (proj) {
    if (proj.id == myid) {
        return proj   // returns Undefined  
    } 
   }); 

Finally, I need to assign that value in a variable to use it later, THANKS :)

Upvotes: 2

Views: 8204

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

I think you're selecting the index successfully, but when you return the value, it goes into a new array ("maps" there if you will). Try something like this:

var myproj; 
var myindex;
projects_array.map(function (proj) {
    if (proj.id == myid) {
        myproj = proj;
        myindex = proj.index;
    } 
}); 

Upvotes: 3

Related Questions