javascript - How to get index of object in array of objects and splice it? -
i'm using angular 1.3, question maybe related javascript.
my candidates array:
var candidates = [ { "attr1": "lu", "attr2": "pizza" }, { "attr1": "gina", "attr2": "sushi" }, { "attr1": "hed", "attr2": "hummus" } ];
my peoples array:
var peoples = [ { "attr1": "bob", "attr2": "pizza" }, { "attr1": "john", "attr2": "sushi" }, { "attr1": "larry", "attr2": "hummus" } ];
and i've checkbox too:
<div class="checkbox" ng-repeat="d in candidates "> <label> <input name="d[]" type="checkbox"ng-click="addremove(d)" ng-value="d"> {{d.attr1}} </label>
so i've function toggles item (from candidates) , want add or remove (if exists)
$scope.addremove = function (item) { var idx = peoples.indexof(item); if (idx > -1) { peoples.splice(idx, 1); } else { peoples.push(item); } };
for reason, if (idx > -1)
never true , keeps add items if exists.
indexof not compare object value instead, compare object reference. can following .
(sorry updated answer "idx" , not if exists )
you can :
var idx = peoples.map(function(p){ return p.attr2;}).indexof(item.attr2); if (idx) { peoples.splice(idx, 1); } else { peoples.push(item); }
Comments
Post a Comment