4

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?

newbie
  • 1,884
  • 7
  • 34
  • 55
  • 3
    That's not an array, that's an object with several properties. This answer may help you: http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip – EfrainReyes Dec 28 '13 at 05:25
  • @EfrainReyes I see. Is there another way than the link you gave? the solution there doesn't support lower version of browser like FF3 that is quite a toll. – newbie Dec 28 '13 at 05:35
  • The marked answer in particular is for newer browsers, but did you check the other answers on that link, and the corresponding comment threads? – EfrainReyes Dec 28 '13 at 05:41
  • By the way, check out this link as well, that approach may work with older browsers: http://stackoverflow.com/a/11369971/2563028 – EfrainReyes Dec 28 '13 at 05:41
  • One more thing before leaving for tonight (it's late here, sorry if I'm commenting too much): The reason why you get 2257 in your last code snippet isn't because that's the sum of all json objects, it's because that's the length of the string generated by converting studentMockBeanMap and all its child objects to a JSON string. – EfrainReyes Dec 28 '13 at 05:49
  • 1
    I'll look into the links you gave. Thanks for your help. – newbie Dec 28 '13 at 05:52

2 Answers2

8

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
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
0

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

http://lodash.com/docs#size

_.size({red: 'red', blue: 'blue'}) // 2
Shanimal
  • 11,517
  • 7
  • 63
  • 76