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?

6
  • 3
    That's not an array, that's an object with several properties. This answer may help you: stackoverflow.com/questions/126100/… Commented Dec 28, 2013 at 5: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. Commented Dec 28, 2013 at 5: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? Commented Dec 28, 2013 at 5:41
  • By the way, check out this link as well, that approach may work with older browsers: stackoverflow.com/a/11369971/2563028 Commented Dec 28, 2013 at 5:41
  • 1
    I'll look into the links you gave. Thanks for your help. Commented Dec 28, 2013 at 5:52

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes. This is what I did just now. Thanks for you help.
0

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

http://lodash.com/docs#size

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.