从jQuery .each()中的javascript对象中删除它
我从以下javascript对象中删除this
(特定的“事件”)时遇到问题, this
是来自jquery .each()
循环。
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" } } }
这是.each()
循环的缩小版本:
$.each(weatherData.events, function(i){ if(this.type == "One Time"){ delete weatherData.events[this]; } })
您正在使用一个需要字符串(属性名称)的对象。 我相信你想:
$.each(weatherData.events, function(i){ if(this.type == "One Time"){ delete weatherData.events[i]; // change is here --------^ } });
…因为$.each
将传递属性名称(例如, "Move Out Day"
)作为迭代器函数的第一个参数,您接受为i
。 因此,要从对象中删除该属性,请使用该名称。
无偿的现场例子 | 资源
您需要项目的名称,而不是对它的引用。 使用回调函数中的参数:
$.each(weatherData.events, function(key, value){ if(value.type == "One Time"){ delete weatherData.events[key]; } });
参考: http : //api.jquery.com/jQuery.each/