Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check this boolean hashmap is empty in javascript? [duplicate]

Possible Duplicates:
Object comparison in JavaScript
How do I test for an empty Javascript object from JSON?

var abc = {};
console.log(abc=={}) //false, why?

Why is it false? How do I match a blank hash map...?

like image 491
TIMEX Avatar asked Oct 10 '22 18:10

TIMEX


1 Answers

{} is a new object instantiation. So abc !== "a new object" because abc is another object.

This test works:

var abc = {};
var abcd = {
  "no": "I am not empty"
}

function isEmpty(obj) {
  for (var o in obj)
    if (o) return false;
  return true;
}

console.log("abc is empty? " + isEmpty(abc))
console.log("abcd is empty? " + isEmpty(abcd))

Update: Just now saw that several others suggested the same, but using hasOwnProperty

I could not verify a difference in IE8 and Fx4 between mine and theirs but would love to be enlightened

like image 189
mplungjan Avatar answered Nov 15 '22 08:11

mplungjan