3
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?

0

1 Answer 1

8

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

might want a check if property exists also so as not to throw error checking length of undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.