码迷,mamicode.com
首页 > Web开发 > 详细

获取json对象长度

时间:2015-09-25 12:42:50      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

 

获取json对象长度

标签:

原文地址:http://www.cnblogs.com/luckythan/p/4837614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!