Ankit Kumar Ankit Kumar - 6 months ago 9
Javascript Question

Deleting an object from a array in javascript

I'm trying to remove an object from the cart using its art_id, but when I'm getting this error

SyntaxError: Delete of an unqualified identifier in strict mode.
Why is this happening and how can I modify my code to come over this error

function remove_from_cart(req, res, next) {
console.log(req.session);
var art_id = req.params._id;

var art_to_remove = _.findWhere(req.session.cart, {
art_id: art_id
});

console.log(art_to_remove);
delete art_to_remove;
console.log(req.session);
res.send('deleted')
}

Answer

Since it seems you're using underscore, you can use _.reject():

req.session.cart = _.reject(req.session.cart, { art_id: art_id });
Comments