请帮帮我,我有这样的angularJS代码:
.state('masterpegawai.alltalenta', {
url: '/alltalenta',
templateUrl: 'public/js/partial-masterpegawai-alltalenta.html',
controller:function($scope,$http,$interval){
$http.get('http://10.16.107.77:3000/allhistorytalenta').success(function(data){
$scope.listtalentapegawai=data;
});
}
})
产生这样的JSON:
[{
"nip": "6080022A",
"nama": "ASLAN PURNAMA",
"semester1_2012": null,
"semester2_2012": null,
"semester1_2013": null,
"semester2_2013": null,
"semester1_2014": null,
"semester2_2014": "Potensial",
"semester1_2015": null
}, {
"nip": "6080022A",
"nama": "ASLAN PURNAMA",
"semester1_2012": null,
"semester2_2012": null,
"semester1_2013": null,
"semester2_2013": null,
"semester1_2014": null,
"semester2_2014": null,
"semester1_2015": "Potensial"
}, {
"nip": "6080038A",
"nama": "SYAIFUL ANWAR",
"semester1_2012": null,
"semester2_2012": null,
"semester1_2013": null,
"semester2_2013": null,
"semester1_2014": null,
"semester2_2014": "Potensial",
"semester1_2015": null
}, {
"nip": "6080038A",
"nama": "SYAIFUL ANWAR",
"semester1_2012": null,
"semester2_2012": null,
"semester1_2013": null,
"semester2_2013": null,
"semester1_2014": null,
"semester2_2014": null,
"semester1_2015": "Potensial"
}, {
"nip": "6080048A",
"nama": "NURHAYATI",
"semester1_2012": null,
"semester2_2012": null,
"semester1_2013": "Potensial",
"semester2_2013": null,
"semester1_2014": null,
"semester2_2014": null,
"semester1_2015": null
}]
我想计算数组键,我的最终结果应该是9
因为每个数组包含9个键
"nip",
"nama",
"semester1_2012",
"semester2_2012",
"semester1_2013",
"semester2_2013",
"semester1_2014",
"semester2_2014",
"semester1_2015"
我是AngularJS的新手,并尝试使用长度方法,但结果总是大于9,因为它计算整个JSON
答案 0 :(得分:4)
您可以使用Object.keys
var length = 0;
Object.keys(o).forEach(function(key) {
var val = o[key];
length = length + 1;
});
o
是任何对象。
在您的情况下,o
应该是数组$scope.listtalentapegawai
的任何对象。
如果你只想要Length
,你可以这样做:
var length = Object.keys(o).length;
.state('masterpegawai.alltalenta', {
url: '/alltalenta',
templateUrl: 'public/js/partial-masterpegawai-alltalenta.html',
controller:function($scope,$http,$interval){
$http.get('http://10.16.107.77:3000/allhistorytalenta').success(function(data){
$scope.listtalentapegawai=data;
var length = Object.keys($scope.listtalentapegawai[0]).length; // will be 9
});
}
})