I have the following json object that im iterating through:
obj = { '19': { id: '19', price: 5.55},
'20': { id: '20', price: 10.00} }
$.each(obj, function(index, value){
if(value.price < 5)
{
delete obj[index];
}
});
I just want to delete an item from the object under certain conditions. In this case, if the price is less than 5.
I've tried delete, but it doesn't do anything.
I have the following json object that im iterating through:
obj = { '19': { id: '19', price: 5.55},
'20': { id: '20', price: 10.00} }
$.each(obj, function(index, value){
if(value.price < 5)
{
delete obj[index];
}
});
I just want to delete an item from the object under certain conditions. In this case, if the price is less than 5.
I've tried delete, but it doesn't do anything.
Share Improve this question edited Mar 16, 2012 at 15:22 Lightness Races in Orbit 385k77 gold badges665 silver badges1.1k bronze badges asked Mar 15, 2012 at 21:27 dzmdzm 23.6k50 gold badges152 silver badges229 bronze badges 1- 1 Your code is correct. (you just don't have any item with price<5) – ori Commented Mar 15, 2012 at 21:30
2 Answers
Reset to default 9Works fine, if the value is < 5
. In your case the value is 5.55
which is > 5
DEMO - To show the object got deleted when the value is < 5
It's possible that jQuery is doing something odd that you don't expect it to. Kind of like how PHP's foreach
creates a copy of the original array to work on.
Try raw JS:
obj = {...};
for( var x in obj) {
if( obj[x].price < 5) delete obj[x];
}
That said, none of your object's prices are less than 5, so obviously none of them will be deleted.