1

I need to evaluate if an object is empty.

For example suppose I have an object:

var home = ....;     // this is an object and after I print it

console.log(home)    // the result of this option is []

//now I need to check if a object is empty or null
if( home == null || home == undefined )
{
    // I don't know specify how object is empty
}

How can I detect whether or not the above object home is null/empty?

9
  • !!home.length ?? Commented Mar 10, 2016 at 14:45
  • Your example is an array, not an object fwiw. Commented Mar 10, 2016 at 14:45
  • @Andy Array is an object. :) Commented Mar 10, 2016 at 14:46
  • Don't confuse the OP. You know what I mean. Commented Mar 10, 2016 at 14:48
  • if I try home.length gives me an error "length is undefined" Commented Mar 10, 2016 at 14:48

2 Answers 2

2

To check for an empty array

if (!arr.length) {
  // if the array is empty
}

and for an object (check that it has no keys)

if (!Object.keys(obj).length) {
  // if the object is empty
}

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

I use all two method and I have the same error, but the vector that I use it is result from var vet = $(this).find('...').map(function() { return { 'name': this.id, 'value': this.value }; }).get();
when the fields are the value the problem doesn't exist,but when I leave the fields empty I have this problem!
At the risk of repeating myself, add the relevant code/HTML to your question. You're now asking about jQuery which doesn't get a mention in your question. If you don't give us all the information, how can we help you?
0

Only way I see so far may be ({}).toSource() === o.toSource()

Example:

var y = {a: 't'};
window.console.log(({}).toSource() === y.toSource());
delete y.a;
window.console.log(({}).toSource() === y.toSource());

EDIT : Oh, nicely found, Andy.

Comments

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.