Austin Lovell
Austin Lovell

Reputation: 1049

Get the length of an array within a JSON object

I want to find out how many items are in my JSON object. I have seen many answers but they all deal with a common value to loop through. I am wanting the results to tell me that there are 2 items in this object. Any help would be great!

[{"manager_first_name":"jim","manager_last_name":"gaffigan"}]

Upvotes: 0

Views: 87

Answers (3)

tewathia
tewathia

Reputation: 7298

Try

var jsonArr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var itemCount = JSON.stringify(jsonArr).split('":"').length - 1;

This is, of course, a rather coarse(and unreliable) way of doing it, but if you just want the item count, this should work like a charm.

Upvotes: 0

Niels
Niels

Reputation: 49909

You can do this:

var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}],
length = 0,
obj = arr[0]; // Get first obj from array

for(var k in obj){
    if( obj.hasOwnProperty(k) ) {
        length++;
    }
}
console.log(length); // Shows 2

You should use hasOwnProperty because you can also extend an Object with functions, there could otherwise also be count als keys.

Links:

Upvotes: 0

adeneo
adeneo

Reputation: 318162

You could use Object.keys in newer browsers. It would return an array of all the keys in the object, and that array would have a length property that will tell you how many items there are in the object :

var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];

var length = Object.keys(arr[0]).length;

FIDDLE

In non-supporting browsers, you have to iterate

var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var i = 0;

for (var key in arr[0]) i++;

FIDDLE

Upvotes: 2

Related Questions