Reputation: 570
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?
Upvotes: 3
Views: 24037
Reputation: 73241
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];
}
Upvotes: 8