JSON Javascript - Property Map - Function reference
I have a JSON object in Javascript like given below:
var myjson={"name":"myname","address":"Myaddress"}
// if my json is not empty:
//do something
I want to find if the object is empty, that is if there are any keys present. How can I do that in Javascript?
Searched in vain through Google Search, but it is tough to say what to search for with so much junk (irrelevant) information coming up.
Is there any official reference for how this works (including delete a key) ? Or am I supposed开发者_开发技巧 to fight with Google Search (no bling for me) and hope for some relevant information?
If you have ECMAScript 5:
Object.keys(myjson).length
will tell you how many (enumerable) properties exist in the object.
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys, where there's also a version you can put in your own code if your browser doesn't support it natively.
The best way to find if a JavaScript object is empty is to use Object.keys, which returns an array of the objects keys (not values).
Object.keys({foo: "bar"}) // returns ["foo"]
Object.keys({}) // returns []
So the easy way to tell if an object has keys is to count the length of that array:
if(Object.keys(myjson).length) {
// this object has keys!
}
As noted in other answers, Object.keys()
should do the trick, but won't work in older browsers that don't support ECMAScript 5. Here's a quick test function that should work cross-browser:
function isEmpty(o) {
// check all keys in the object
for (var key in o) {
// but don't go up the prototype chain
if (o.hasOwnProperty(key)) {
// if found, stop right away
return false;
}
}
return true;
}
if you're the kind of person who likes tighter, less verbose code, you could write it like this:
function isEmpty(o) {
for (var key in o) if (o.hasOwnProperty(key)) return false;
return true;
}
精彩评论