Reputation: 51937
I have a global object MyFruits that can have multiple properties. At a minimum, it has two properties: Apples and Oranges. I need to find out if it has more properties than just these two.
For the moment, I stringify MyFruits, create a new object with just the Apples and Oranges properties and stringify it too and compare the length of both strings. Something like this:
var JsonString1 = JSON.stringify(MyFruits);
var test2 = new Object();
test2.Apples= MyFruits.Apples;
test2.Oranges= MyFruits.Oranges;
var JsonString2= JSON.stringify(test2);
alert(JsonString1.length - JsonString2.length);
For now, it initially seems like it's working: if MyFruits contains more properties than just the two main ones, the difference of length will be different from 0.
There's the Object.keys(obj).length
method that can count the number of properties of an object but it's new and not supported in all browsers so I'm not going to use it.
Is this the best way to do it? Let me know if there's a better way.
Thanks for your suggestions.
Upvotes: 0
Views: 208
Reputation: 29381
If you only want the enumerable keys of an object, I would consider extending the Object when Object.keys() if not implemented instead of using the JSON object (which isn't available in all major browsers either).
if (typeof Object.keys === 'undefined') {
Object.keys = function (obj) {
var keys = [];
for (var property in obj) {
keys.push(property);
}
return keys;
}
}
Now you will always be able to call Object.keys(yourObject)
and get the list of object keys.
Upvotes: 0
Reputation: 348992
Instead of serializing the object, you'd better loop through the object, and check if there's any property which is not Apples
or Oranges
:
for (var i in MyFruits) {
if (MyFruits.hasOwnProperty(i) && i !== 'Apples' && i !== 'Oranges') {
throw 'Not expected!'; // Do something, eg: error_flag=true;break;
}
}
Upvotes: 2
Reputation: 754725
In order to see if it has more than just 2 properties just enumerate the properties and see if more than 2 are present.
var count = 0;
for (var name in test2) {
if (test2.hasOwnProperty(name)) {
count++;
if (count > 2) {
break;
}
}
}
if (count > 2) {
// Has more than 2 properties
}
Upvotes: 3