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?

MFerguson
  • 1,739
  • 9
  • 17
  • 30
user6045391
  • 51
  • 1
  • 7

2 Answers2

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

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 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(); – user6045391 Mar 10 '16 at 15:26
  • when the fields are the value the problem doesn't exist,but when I leave the fields empty I have this problem! – user6045391 Mar 10 '16 at 15:27
  • 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? – Andy Mar 10 '16 at 15:31
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.

capqch
  • 46
  • 2