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.
Instead of serializing the object, you’d better loop through the object, and check if there’s any property which is not
ApplesorOranges: