Remove item from json object

I have the following json object that runs with:

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 remove an element from an object under certain conditions. In this case, if the price is less than 5.

I tried to delete, but does nothing.

+5
source share
2 answers

Works well if value < 5. In your case, the value 5.55that> 5

DEMO - to show that the object was deleted when the value< 5

+9
source

It is possible that jQuery is doing something weird that you don't expect. As if PHP was foreachcreating a copy of the original array to work.

Try raw JS:

obj = {...};
for( var x in obj) {
    if( obj[x].price < 5) delete obj[x];
}

, 5, , , .

0

All Articles