1

I have object created by function:

$scope.checkPosRole = function(possition , posRole , posFunction) {
   var rolePos = {pos: possition, posRole: posRole, posFunction: posFunction}; 
   $scope.rolePossition.push(rolePos);
   };

The problem is that I want to in the array was only 1 object with the specified value of pos. In the case when the object is added with value pos that exists already in the array I want to swap new object with object exist already in array.

I've tried every function call scan the tables with foreach, but did not bring me desirable effect. Please help.

justcurious
  • 839
  • 3
  • 12
  • 29
Daniel Siwek
  • 23
  • 1
  • 3
  • 4
    Possible duplicate of [add only unique objects to an array in JavaScript](http://stackoverflow.com/questions/17350363/add-only-unique-objects-to-an-array-in-javascript) – Rahul Tripathi Nov 05 '15 at 14:04
  • Does the *order* of items matter? If not, simply use an object instead of an array: `rolePositions[rolePos.position] = rolePos`. – deceze Nov 05 '15 at 14:06
  • Possible duplicate of [Merge duplicate objects in array of objects](http://stackoverflow.com/questions/30025965/merge-duplicate-objects-in-array-of-objects) – Krzysztof Safjanowski Nov 05 '15 at 14:06

1 Answers1

4

try this

var rolePosition = [{ id: 1}, {id: 2}, {id: 3}];

function addRolePosition(data) {
  var index = -1;
  
  for(var i = 0, i < rolePosition.length; i++) {
    if(rolePosition[i].id === data.id) {
      index = i;
    }
  }
  
  if(index > -1) {
    rolePosition[index] = data;
  } else {
    rolePosition.push(data)
  }
}
Hitmands
  • 13,491
  • 4
  • 34
  • 69