newbie
newbie

Reputation: 1980

JSON array get length using jQuery or javascript

I know there are many similar questions to this. But any of them doesn't work for me.

I have a json array which the whole structure is like this:

enter image description here

The array the i want to get is this:

enter image description here

The structure of that json array is:

enter image description here

I want to get the length of that json array. In the image case above it is 4. What I tried so far is this:

console.log( $( data.studentMockBeanMap ).size() );
console.log( $(data.studentMockBeanMap ).length );.

Which both returns 1

I also try this one:

var x = JSON.stringify(data.studentMockBeanMap);
console.log( x.length );

Which returns 2257, which IMO it also returns the sum of all json object.

How can I only the size on the image i boxed above?

Upvotes: 4

Views: 27875

Answers (2)

Shanimal
Shanimal

Reputation: 11718

You can also use the lodash library (which has a size function).

http://lodash.com/docs#size

_.size({red: 'red', blue: 'blue'}) // 2

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19772

This does the same think as Object.keys(obj).length, but without the browser compatibility issue (I think).

What about:

var obj = {
    yo: {
         a: 'foo',
         b: 'bar'
    }
    hi: {
        c: 'hello',
        d: 'world',
        e: 'json'
    }
}

var arr = [], len;

for(key in obj) {
    arr.push(key);
}

len = arr.length;

console.log(len) //2

OR

var arr = [], len;

for(key in obj.hi) {
    arr.push(key);
}

len = arr.length;

console.log(len) //3

OR, in your case

var arr = [], len;

for(key in studentMockBeanMap) {
    arr.push(key);
} 

len = arr.length;

console.log(len); //4

Upvotes: 8

Related Questions