I have an array of objects:
Object = { 1 : { name : bob , dinner : pizza }, 2 : { name : john , dinner : sushi }, 3 : { name : larry, dinner : hummus } }
I want to be able to search the object/array for where the key is "dinner", and see if it matches "sushi".
I know jQuery has $.inArray, but it doesn't seem to work on arrays of objects. Or maybe I'm wrong. indexOf also seems to only work on one array level.
Is there no function or existing code for this?
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
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" }]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With