1

Following Situation:

role: { roleid=3,  name="admin"}

availableRoles:
    [
        { roleid=3,  name="admin",  $$hashKey="object:222"}, 
        { roleid=4,  name="plain user",  $$hashKey="object:223"}
    ]

currentRoles: 
    [
        { roleid=3,  name="admin"}
    ]

Following Trys:

currentRoles.indexOf(role);  // works properly and outputs 0
availableRoles.indexOf(role);  // does not work 

I can imagine, this occurs because of $$hasKeys. But I didn't put them there, AngularJS does augment these data.

How can I overcome this situation?

Is there a function like: ignore Angular HasKeys in this Datastructure?

  • 1
    You can itearate with help of angular foreach. Directly you can't check it beacuse indexof works direct array not an aray contain objects. – Sudharsan S Dec 14 '15 at 13:51

2 Answers2

3

Edit:

Angular object comparison: Compare objects in Angular

So you can just write the function:

function arrayObjectIndexOf(arr, obj){
    for(var i = 0; i < arr.length; i++){
        if(angular.equals(arr[i], obj)){
            return i;
        }
    };
    return -1;
}

--ORIGINAL--

JavaScript saves objects as pointers, therefore, two objects even if has the same data in them, have different values (the value of the pointer in the memory).

Code example:

var role = { roleid:3,  name:"admin"};

var availableRoles =
    [
        { roleid:3,  name:"admin"}, 
        { roleid:4,  name:"plain user",  $$hashKey:"object:223"}
    ];
alert(availableRoles.indexOf(role));

http://codepen.io/anon/pen/BjobaW

So it does not relate to the hashKey. To compare to objects (and such, find the index in an array) you must create a loop of comparison, or overload the "==" operator of Object to compare values and not pointers, which I dont believe you are allowed to do in JS.

Community
  • 1
  • 1
Amit
  • 5,924
  • 7
  • 46
  • 94
  • We are here within Angular, there should be maybe an Angular Solution? –  Dec 14 '15 at 13:58
0
  • Best way is not to have such objects...

  • You can use angular filter:

function contains(arr, id) {
    return $filter('filter')(arr, {roleid : id}, true).length != 0;
}
  • You can use some other js library (lodash, underscore, ...) for such things.
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38