Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery how to find an Object by attribute in an Array

Given I have an array of "purpose" objects:

//array of purpose objects: var purposeObjects = [     {purpose: "daily"},     {purpose: "weekly"},     {purpose: "monthly"} ]; 

(for simplicity i am omitting other attributes)

Now I want to have a method that returns a specific one of the objects if a matching purpose name is found.

This is not working:

function findPurpose(purposeName){     return $.grep(purposeObjects, function(){       return this.purpose == purposeName;     }); };  findPurpose("daily"); 

but it actually returns an empty array:

[] 

I am using JQuery 1.5.2. I have also tried with $.each() but with no luck. Apparently, most JQuery methods are designed for usage with DOM elements (such as filter().

Any ideas on how to achieve this?

like image 598
Jesper Rønn-Jensen Avatar asked Apr 07 '11 10:04

Jesper Rønn-Jensen


People also ask

How do I find a specific object in an array?

To find an object in a JavaScript array, use the array. find() method. The find() method searches the provided object inside the array, and if the method finds it, it returns the object.

How do you check if an element is present in an array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

What is grep function in jQuery?

grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.


2 Answers

No need for jQuery.

JavaScript arrays have a find method, so you can achieve that in one line:

array.find((o) => { return o[propertyName] === propertyValue }) 

Example

 const purposeObjects = [     {purpose: "daily"},     {purpose: "weekly"},     {purpose: "monthly"} ];  purposeObjects.find((o) => { return o["purpose"] === "weekly" })        // output -> {purpose: "weekly"} 

If you need IE compatibility, import this polyfill in your code.

like image 191
Luca Fagioli Avatar answered Sep 22 '22 06:09

Luca Fagioli


you should pass reference on item in grep function:

function findPurpose(purposeName){     return $.grep(purposeObjects, function(item){       return item.purpose == purposeName;     }); }; 

Example

like image 25
Andrei Avatar answered Sep 23 '22 06:09

Andrei