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?

Use this function:

function findObjectInArrayByProperty(array, propertyName, propertyValue) {
    return array.find((o) => { return o[propertyName] === propertyValue });
}

So, in your case:

const purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

findObjectInArrayByProperty(purposeObjects, "purpose", "weekly");

// output -> {purpose: "weekly"}

More about the find method here.

Find object by id in an array of JavaScript objects, The find() method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned. If you want to find its index instead, use findIndex() : myArray. Note. jQuery $.grep (or other filtering function) is not the optimal solution. The $.grep function will loop through all the elements of the array, even if the searched object has been already found during the loop.

you should pass reference on item in grep function:

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

Example

JavaScript: find an object in array based on object's property (and , JavaScript: find an object in array based on object's property (and learn jQuery's grep function to achieve our desired result, it goes like this: If we opt to use Underscore.js, our code to find the object with the id equal to 3 changes to this: var obj = _.find(objArray, function (obj) { return obj.id === 3; }); Using jQuery

I personally use a more generic function that works for any property of any array:

function lookup(array, prop, value) {
    for (var i = 0, len = array.length; i < len; i++)
        if (array[i] && array[i][prop] === value) return array[i];
}

You just call it like this:

lookup(purposeObjects, "purpose", "daily");

jQuery.grep(), The array-like object to search through. function. Type: Function( Object elementOfArray, Integer indexInArray ) => Boolean. The function to process each item� From MDN: The findIndex () method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned. If you want to get an array of matching elements, use the filter () method instead: myArray.filter(x => x.id === '45'); This will return an array of objects.

The error was that you cannot use this in the grep, but you must use a reference to the element. This works:

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

findPurpose("daily");

returns:

[Object { purpose="daily"}]

.filter(), Given a jQuery object that represents a set of DOM elements, the .filter() method as it uses the modulus operator ( % ) to select every item with an index value that, the resulting jQuery object only if it matches one of the nodes in the filtering array. Class Attribute � Copying � DOM Insertion, Around � DOM Insertion, Inside� jQuery Arrays: Mapping an Array . The jQuery method $.map() method lets you use a function to project the contents of an array or a map object into a new array, using a function to determine how each item is represented in the result. Example: Mapping an Array using jQuery

Use the Underscore.js findWhere function (http://underscorejs.org/#findWhere):

var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

var daily = _.findWhere(purposeObjects, {purpose: 'daily'});

daily would equal:

{"purpose":"daily"}

Here's a fiddle: http://jsfiddle.net/spencerw/oqbgc21x/

To return more than one (if you had more in your array) you could use _.where(...)

jQuery.inArray(), indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value , $.inArray() returns 0. Because JavaScript� Given an array of objects and the task is to get the maximum and minimum value from the array of objects. There are a few methods used which are discussed below: Javascript apply() method: It is write method which is used on different objects.

.find(), An element or a jQuery object to match elements against. Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search� I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.

.map(), A function object that will be invoked for each element in the current set. If you wish to process a plain array or object, use the jQuery.map() instead. As the return� The find () method returns the value of the first element in an array that pass a test (provided as a function). The find () method executes the function once for each element present in the array:

jQuery.map(), Array-like objects — those with a .length property and a value on the .length - 1 index — must be converted to actual arrays before being passed to $.map� jQuery.each(array, callback) // or for objects it can be used as jQuery.each(object, callback) where, array parameter will have the array and the callback will be a function with parameters index and item, where index will store the index of the array in each iteration and i tem will store the data element.

Comments
  • I think if (purposeObjects[i].purposeName === purposeName) should read if (purposeObjects[i].purpose === purposeName)
  • this is the best and optimal solution !! u rock pal
  • exactly! That was just what I ended up doing.
  • The $.grep function will loop through all the elements of the array, even if the searched object has been already found during the loop. It is not optimal. Check out my answer.
  • Totally agreeing with Luca: $.grep() loops thru the whole object, even if you return in the conditional! In smaller objects, this might be unimportant, but what if the object is really big, like a Calendar till 2034? I'd opt for Luca Fagioli's solution to be the best answer
  • Some set of circumstances prevents this from working 100% of the time. I have a handful of methods that rely on this method - called by some method, it always works, other methods it never works. I'm logging all calls and can not see a visible difference from 'works' to 'doesn't. This output show the third iteration should satisfy the test and return 3.true array[i][prop]: 19741 val: 19741
  • The $.grep function will loop through all the elements of the array, even if the searched object has been already found during the loop. It is not optimal. Check out my answer.
  • Totally agreeing with Luca: $.grep() loops thru the whole object, even if you return in the conditional! In smaller objects, this might be unimportant, but what if the object is really big, like a Calendar till 2034? I'd opt for Luca Fagioli's solution to be the best answer