JSON 数组使用 jQuery 或 javascript 获取长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20811318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:19:04  来源:igfitidea点击:

JSON array get length using jQuery or javascript

jqueryarraysjson

提问by newbie

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:

我有一个 json 数组,整个结构是这样的:

enter image description here

在此处输入图片说明

The array the i want to get is this:

我想得到的数组是这样的:

enter image description here

在此处输入图片说明

The structure of that json array is:

该 json 数组的结构是:

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:

我想获取该 json 数组的长度。在上面的图像案例中,它是4。到目前为止我尝试过的是:

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

Which both returns 1

两者都返回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.

它返回2257,IMO 它还返回所有 json 对象的总和。

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

我怎样才能只有我在上面装箱的图像上的尺寸?

回答by Josh Beam

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

这与Object.keys(obj).length 的想法相同,但没有浏览器兼容性问题(我认为)。

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

回答by Shanimal

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

你也可以使用 lodash 库(它有一个 size 函数)。

http://lodash.com/docs#size

http://lodash.com/docs#size

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