Reputation: 9080
I'm trying to remove an object list item in javascript:
$(document).ready(function () {
var eventObjs = [];
var idVal = 0;
$("#addItem").click(function () {
eventObjs.push([{ title: 'test', personId: idVal }]);
idVal += 1;
});
$("#removeItem").click(function () {
idVal -= 1;
eventObjs = eventObjs
.filter(function (el) {
return el.personId !== (idVal - 1);
});
$("#arrVal").html(eventObjs.length);
});
});
Fiddle: http://jsfiddle.net/webdad3/51vbzne1/2/
I can add my elements just fine. But when I try to remove them. Nothing works. Where am I going wrong?
I got the code to remove items from the array from an example. Maybe the question isn't what am I doing wrong with the above, but what do I need to do to remove item from my list?
Upvotes: 0
Views: 257
Reputation: 3994
This is because your filter condition is wrong.
Here is the correct version: http://jsfiddle.net/51vbzne1/3/
eventObjs = eventObjs.filter(function (el) {
return el.personId <= idVal;
});
Explanation: you should filter to check that every personId
is lower than the current idVal
. Since you are doing the idVal -= 1
before filtering, you need to use <=
.
Or if you want to remove a specific item. Use splice, eg: eventObjs.splice(idVal, 1);
Upvotes: 1
Reputation: 1
Try
$(document).ready(function () {
var eventObjs = [];
var idVal = 0;
$("#addItem").click(function () {
eventObjs.push([{
title: 'test', personId: idVal
}]);
idVal += 1;
alert(eventObjs.length);
});
$("#removeItem").click(function () {
eventObjs.splice(-1);
idVal = idVal -1;
alert(idVal);
});
});
jsfiddle http://jsfiddle.net/51vbzne1/5/
Upvotes: 2
Reputation: 1633
Replace eventObjs.push([{ title: 'test', personId: idVal
}]);
with eventObjs.push({ title: 'test', personId: idVal });
. Now you have something like [[{title: 'test1'}], [{title: 'test2'}]]
, instead of [{title: 'test1'}, {title: 'test2'}]
Replace return el.personId !== (idVal - 1);
with return
el.personId !== idVal;
Upvotes: 1