Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the indexOf an object within an AngularJS response object collection?

Use Case

I have a collection of objects returned from a REST request. Angular automatically populates each element with a $$hashKey. The problem is that when I search for an object in that array without the $$hashKey, it returns -1. This makes sense. Unfortunately, I don't have knowledge of the value of $$hashKey.

Question

Is there a more effective way to search for an object within an object collection returned from a REST request in AngularJS without stripping out the $$hashKey property?

Code

function arrayObjectIndexOf(arr, obj) {
var regex = /,?"\$\$hashKey":".*?",?/;
    var search = JSON.stringify(obj).replace(regex, '');
    console.log(search);
    for ( var i = 0, k = arr.length; i < k; i++ ){
        if (JSON.stringify(arr[i]).replace(regex, '') == search) {
            return i;
        }
    };
    return -1;
};
like image 382
Pete Avatar asked Apr 16 '14 21:04

Pete


People also ask

How do I find the index of an element in an object?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How to get index of an element in js?

JavaScript Array findIndex() The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found.

How to get index of item in array js?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.


1 Answers

angular.equals() does a deep comparison of objects without the $ prefixed properties...

function arrayObjectIndexOf(arr, obj){
    for(var i = 0; i < arr.length; i++){
        if(angular.equals(arr[i], obj)){
            return i;
        }
    };
    return -1;
}
like image 196
Anthony Chu Avatar answered Oct 17 '22 10:10

Anthony Chu