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];
}
Comments
-
Luvias almost 2 years
obj = {a: []}
I want to delete
obj.a
. This code worksif(!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 almost 6 yearsmight want a check if property exists also so as not to throw error checking length of undefined