4

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

This would work but how do I find the index of the object, with only the name of the object given?
this would work, but I like the above answer better, it's simpler and to the point. Thanks though!
@dalton, no problem. this is just an alternative. Note that my implementation modifies the actual array, filter creates a new array.
Yes, but it all works out if you're replacing the old array with the new array, doesn't it?
@DaltonGore: Not if there are other references to the original Array. They'll still be holding on to the old one. Probably safer to modify the original unless you can absolutely guarantee that no other code keeps a reference to global.menu.
|
2

use filter and re-assign

global.menu = global.menu.filter(function(a){ return a.item != "be delete" };

4 Comments

This looks like it would delete the entire array, whereas I would only need to delete the object with selected name.
delete one item is equal to select other item without delete item. it's simple solution using list
OHHHHHH. Derp. I just actually LOOKED at the code, thanks this is exactly what I'm looking for. Derp derp derp.
If there are any other references to the original global.menu Array, they'll remain unmodified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.