Javascript JSON 对象的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3241782/
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-23 03:49:39  来源:igfitidea点击:

Length of a JSON object

javascriptjson

提问by Rodrigo

This function is generating a array with json objects on it:

此函数正在生成一个带有 json 对象的数组:

var estoque={};
function unpack_estoque(tnm,total,estoque_vl,id,tid,st) {
    tnm=tnm.split("|");
    total=total.split("|");
    estoque_vl=estoque_vl.split("|");
    id=typeof id != 'undefined' ? id.split("|") : null;
    tid=typeof tid != 'undefined' ? tid.split("|") : null;
    st=typeof st != 'undefined' ? st.split("|") : null;

    for (var i in tnm)
        estoque[i]={
            "id": id != null ? id[i] : null,
            "tid": tid != null ? tid[i] : null,
            "total": total[i],
            "estoque": estoque_vl[i],
            "tnm": tnm[i],
            "st": st != null ? st[i] : null
        };
}

Now how do i get the estoquelength to loop through the collected items?

现在我如何获得estoque循环遍历收集的项目的长度?

estoque.lengthreturns undefinedwhile for (var i in estoque)loops through JSON object and not estoque[] root array.

estoque.length返回undefinedwhilefor (var i in estoque)循环遍历 JSON 对象而不是 estoque[] 根数组。

Thanks.

谢谢。

采纳答案by Andreas

var estoque = {}; //object estoque.length will not work (length is an array function)
var estoque = new Array(); //estoque.length will work

You could try:

你可以试试:

 var estoque = new Array();
 for (var i in tnm)
    estoque.push({
        "id": id != null ? id[i] : null,
        "tid": tid != null ? tid[i] : null,
        "total": total[i],
        "estoque": estoque_vl[i],
        "tnm": tnm[i],
        "st": st != null ? st[i] : null
    });

Now estoque will be an array (which you can traverse as one).

现在 estoque 将是一个数组(您可以将其作为一个遍历)。

回答by John

You will not get that to work as it is an array method, not an object. You can use the length property of tnm as your measure. Then you can you can use:

你不会让它工作,因为它是一个数组方法,而不是一个对象。您可以使用 tnm 的长度属性作为度量。然后你可以使用:

var tnmLength = tnm.length;
for (i=0, i>tnmLength - 1; i++) {
     estoque[tnm[i]] = {};
}

To loop through all of the items in the tnm array.

循环遍历 tnm 数组中的所有项目。

回答by MrBii

a={a:{},b:{},c:{}}
Object.keys(a).length
3