Delete this from a javascript object in a jQuery .each()

被刻印的时光 ゝ 提交于 2019-12-10 13:17:51

问题


I am having trouble deleting this (a specific 'event') from the following javascript object, when this is from a 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 shrunken version of the .each() loop:

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

回答1:


You're using an object where a string (the property name) is expected. 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 in the property name (e.g., "Move Out Day") as the first argument to the iterator function, which you're accepting as i. So to delete that property from the object, you use that name.

Gratuitous live example | source




回答2:


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

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

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



来源:https://stackoverflow.com/questions/10680892/delete-this-from-a-javascript-object-in-a-jquery-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!