最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can i find the length of this Json object - Stack Overflow

programmeradmin2浏览0评论

I want to find the length of this JSON object so any one tell me how can i get length of the JSON object...means i want to know how many data this json object contain.

var ddData = [{ "01":"United States",
                "02":"United Kingdom",
                "03":"Aruba",
                "04":"United Kingdom",
                "05":"Aruba",
                "06":"Bahrain",
                "07":"United Kingdom",
                "08":"Algeria",
                "09":"Andorra",
                "10":"American Samoa",
                "11":"United States"
             }]

I want to find the length of this JSON object so any one tell me how can i get length of the JSON object...means i want to know how many data this json object contain.

var ddData = [{ "01":"United States",
                "02":"United Kingdom",
                "03":"Aruba",
                "04":"United Kingdom",
                "05":"Aruba",
                "06":"Bahrain",
                "07":"United Kingdom",
                "08":"Algeria",
                "09":"Andorra",
                "10":"American Samoa",
                "11":"United States"
             }]
Share Improve this question edited Mar 2, 2016 at 2:50 computingfreak 5,0991 gold badge37 silver badges52 bronze badges asked Jan 11, 2013 at 5:44 codercoder 1,8923 gold badges22 silver badges32 bronze badges 0
Add a comment  | 

6 Answers 6

Reset to default 12

You could use Object.keys method to get the object keys.
Since ddData is an array, and the first index contains an object, you could do this :

Object.keys(ddData[0]).length;

However, Object.keys does not work on old browsers.

For that, you could iterate through the object and increment a variable to get the length of that object.

var count = 0;
for(var i in ddData[0]) {
    count++;
}

You can use the Object.keys that will return the length of specified collection.JS Fiddle.

(Browser support from here) (Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

you can simply do this instead of calling functions

var key, count = 0;
for(key in ddData[0]) {
  count++;
}

console.log(count + " is size of the json");
var length=0;
for(attr in ddData[0]){
     length++;
}
var json = JSON.parse(ddData);
for(i=0;i<json.length;i++)
{
alert(json[i].length);
}

Now i got the answer....

var Data = { "01":"United States",
            "02":"United Kingdom",
            "03":"Aruba",
            "04":"United Kingdom",
            "05":"Aruba",
            "06":"Bahrain",
            "07":"United Kingdom",
            "08":"Algeria",
            "09":"Andorra",
            "10":"American Samoa",
            "11":"United States"
         }

var count = 0;
for(x in Data){
    count++;
}
console.log('cnt',count)
发布评论

评论列表(0)

  1. 暂无评论