Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find specific key value in array of objects

This is the code:

var groups = {
    "JSON":{
        "ARRAY":[
            {"id":"fq432v45","name":"Don't use me."},

            {"id":"qb45657s","name":"Use me."}
        ]
    }
}

I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?

Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.

like image 203
Garrett R Avatar asked Jun 16 '26 10:06

Garrett R


1 Answers

You can simply filter on the given id:

groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });

This will return [{"id":"qb45657s","name":"Use me."}]

like image 67
mVChr Avatar answered Jun 17 '26 23:06

mVChr