获取json对象长度

JSON对象变化万千,非常灵活,对应的获取方法分别为:

1.最简单类型的(myObject是对象,不是字符串哦)

<script type="text/javascript">

    var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}

    var count = Object.keys(myObject).length
    console.log(count);
</script>

在较老版本的浏览器中需加入以下代码确保可以使用:

if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                keys.push(k);
            }
        }
        return keys;
    };
}

2.ajax请求返回的值形式:

{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}

遍历之:

var key, count = 0;
for(key in data.phones) {
  if(data.phones.hasOwnProperty(key)) {
    count++;
  }
}

3.更多方法stackoverflow

http://stackoverflow.com/questions/6756104/get-size-of-json-object
http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascript/4889658#4889658

 

posted @ 2015-09-25 11:11  luckymore  阅读(14281)  评论(8编辑  收藏  举报