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?
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.
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.
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.
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.
you should pass reference on item in grep function:
function findPurpose(purposeName){ return $.grep(purposeObjects, function(item){ return item.purpose == purposeName; }); };
Example
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