I'm trying to figure out how many properties are in the following object. Obviously, I can see 2, but I need to know dynamically.
var test = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }');
If I try:
var mylen = test.length;
.length is undefined. The number of properties in this object will change. Sometimes it's 1, sometimes 2 or 3, but I just can't figure out how to test it.
解决方案
This is a JavaScript JSON object. length function is not available.
First solution with pure JavaScript:
var data = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }');
var keys = [];
for (key in data) {
keys.push(key);
}
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;
Second solution if you prefer jQuery:
var data = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }');
var keys = [];
$.each(data, function(key, value) {
keys.push(key)
});
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;