How to find a value in an array of objects in JavaScript?
If you have an array such as
var people = [ { "name": "bob", "dinner": "pizza" }, { "name": "john", "dinner": "sushi" }, { "name": "larry", "dinner": "hummus" }];
You can use the filter
method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" }); // => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations you can use a function expression:
people.filter(p => p.dinner == "sushi") // => [{ "name": "john", "dinner": "sushi" }]
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) { if (person.dinner == "sushi") { return person } else { return null }}); // => [null, { "name": "john", "dinner": "sushi" }, null]
or a reduce
people.reduce(function (sushiPeople, person) { if (person.dinner == "sushi") { return sushiPeople.concat(person); } else { return sushiPeople }}, []); // => [{ "name": "john", "dinner": "sushi" }]
I'm sure you are able to generalize this to arbitrary keys and values!
jQuery has a built-in method jQuery.grep
that works similarly to the ES5 filter
function from @adamse's Answer and should work fine on older browsers.
Using adamse's example:
var peoples = [ { "name": "bob", "dinner": "pizza" }, { "name": "john", "dinner": "sushi" }, { "name": "larry", "dinner": "hummus" }];
you can do the following
jQuery.grep(peoples, function (person) { return person.dinner == "sushi" }); // => [{ "name": "john", "dinner": "sushi" }]
var getKeyByDinner = function(obj, dinner) { var returnKey = -1; $.each(obj, function(key, info) { if (info.dinner == dinner) { returnKey = key; return false; }; }); return returnKey; }
So long as -1
isn't ever a valid key.