json的长度达到特定键

时间:2014-04-17 18:22:18

标签: javascript json

让我们说这是我的变量,我是通过.serializeArray()

创建的
 a={"acctType1":"individual","compare_act1":"contains","match_name_act1":"accountName","text_act1":"","acctType2":"individual","compare_act2":"contains","match_name_act2":"accountName","text_act2":"","transType1":"401kContribution","compare_trans1":"contains","match_name_trans1":"description","text_trans1":"","transType2":"401kContribution","compare_trans2":"contains","match_name_trans2":"description","text_trans2":""}

所以这个长度是= 16。

使用:

  

Object.keys的(a)。长度;

我想知道长度只有transtype1,在这种情况下应该是8,我该如何找到它。

另一个例子:

b={"acctType1":"individual","compare_act1":"contains","match_name_act1":"accountName","text_act1":"","acctType2":"individual","compare_act2":"contains","match_name_act2":"accountName","text_act2":"","acctType3":"individual","compare_act3":"contains","match_name_act3":"accountName","text_act3":"","acctType4":"individual","compare_act4":"contains","match_name_act4":"accountName","text_act4":"","acctType5":"individual","compare_act5":"contains","match_name_act5":"accountName","text_act5":"","transType1":"401kContribution","compare_trans1":"contains","match_name_trans1":"description","text_trans1":"","transType2":"401kContribution","compare_trans2":"contains","match_name_trans2":"description","text_trans2":"","transType3":"401kContribution","compare_trans3":"contains","match_name_trans3":"description","text_trans3":""}

长度b = 32

但是transtype1的长度是20

提前致谢

2 个答案:

答案 0 :(得分:1)

对象没有内在顺序,因此其中的属性没有数字位置。

您可以使用for in循环计数,直到找到您要查找的项目为止,但无法保证您获得的结果与源顺序一致,即前一循环的顺序围绕物体或其他任何东西。

答案 1 :(得分:0)

正如@Quentin所说,你不能确定用for循环会给你正确的对象顺序,你应该以其他方式存储你的数据。如果你仍想这样做,你可以这样做:

function lengthUpTo(obj,key){
    var count=0;
    for(var i in obj){
        if(i==key) return count;
        count++
    }
    return -1;
}
console.log(lengthUpTo(b,"transType1"))//20
console.log(lengthUpTo(b,"nonExistant"))//-1