Cannot delete object property in Javascript

13,028

You can't delete [], which is all that you pass to the function.

You can create a function like

function _delete(obj, prop) {
    if (obj[prop] && ! obj[prop].length) delete obj[prop];
}

and call it with

_delete(obj, 'a');

I'd also add a check for what the property is, and if it exists at all. As you seem to target an array, add a check if it's an array that gets passed:

function _delete(obj, prop) {
    if (Array.isArray(obj[prop]) && ! obj[prop].length) delete obj[prop];
}
Share:
13,028
Luvias
Author by

Luvias

I'm a newbie in PHP.

Updated on June 26, 2022

Comments

  • Luvias
    Luvias almost 2 years
    obj = {a: []}
    

    I want to delete obj.a. This code works

    if(!obj.a.length)
        delete obj.a //work
    

    This is not

    function _delete(o) {
        if(!o.length)
          delete o 
    }
    
    _delete(obj.a) //not work
    

    Any way to make it works?

  • charlietfl
    charlietfl almost 6 years
    might want a check if property exists also so as not to throw error checking length of undefined