Possible Duplicate:
JavaScript Array Delete Elements
So, in javascript, I have this set up:
global.menu = [{
name: item1,
price: price1,
message: message1
},
{
name: item2,
price: price2,
message: message2
},
{
name: item3,
price: price3,
message: message3
}];
And my question is pretty simple, but how would I delete an object from this array?
To select an object, I'm using this command:
global.HandleMenu = function (b) {
var c = menu.filter(function (d) {
return d.name == b;
});
c.forEach(function (d) {
Say(d.message);
});
};
So yeah. Can I just add delete d;, or d.remove() inside the forEach function? Or am I missing something?
Assuming the name of the item you want to delete is in a variable called name
, something like
for (var i = 0; i = global.menu.length - 1; i--) {
var current = global.menu[i];
if (current.name === name) global.menu.splice(i, 1);
}
should work. Note I'm not testing for nulls; but this is the general idea.
use filter and re-assign
global.menu = global.menu.filter(function(a){ return a.item != "be delete" };