Remove this from javascript object in jQuery.each ()

I am unable to remove this (specific "event") from the next javascript object when this is from the jquery .each() loop.

weatherData:

 { "events":{ "Birthday":{ "type":"Annual", "date":"20120523", "weatherType":"clouds", "high":"40", "low":"30", "speed":"15", "direction":"0", "humidity":"0" }, "Move Out Day":{ "type":"One Time", "date":"20120601", "weatherType":"storm", "high":"80", "low":"76", "speed":"15", "direction":"56", "humidity":"100" } }, "dates":{ "default":{ "type":"clouds", "high":"40", "low":"30", "speed":"15", "direction":"0", "humidity":"0" }, "20120521":{ "type":"clear", "high":"60", "low":"55", "speed":"10", "direction":"56", "humidity":"25" } } } 

This is a shortened version of the .each() loop:

 $.each(weatherData.events, function(i){ if(this.type == "One Time"){ delete weatherData.events[this]; } }) 
+6
source share
2 answers

You are using an object where a string is expected (property name). I believe you want:

 $.each(weatherData.events, function(i){ if(this.type == "One Time"){ delete weatherData.events[i]; // change is here --------^ } }); 

... because $.each will pass the name of the property (for example, "Move Out Day" ) as the first argument to the iterator function, which you take as i . Thus, to remove this property from an object, you use this name.

Useless living example | a source

+7
source

You need the name of the element, not a link to it. Use the parameters in the callback function:

 $.each(weatherData.events, function(key, value){ if(value.type == "One Time"){ delete weatherData.events[key]; } }); 

Link: http://api.jquery.com/jQuery.each/

+1
source

Source: https://habr.com/ru/post/916227/


All Articles