这是我的json数组我需要计算projectid(不是数组的长度)。我期待计数是2因为
[{
"oid": "1",
"oname": "Fontbyte",
"bun": [{
"projectid": "1",
"bname": "euuu",
"dep": [{
"did": "1",
"dname": "Development department"
}, {
"did": "2",
"dname": "prod"
}]
}, {
"projectid": "2",
"bname": "USs",
"dep": []
}]
}]

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
数组有2个projectid.how它可能是jquery还是javascript?
答案 0 :(得分:1)
尝试循环对象,如:
count = 0;
$.each(obj[0].bun,function(i,v){
$.each(v,function(x,t){
if (x == 'projectid') {
count+=1
};
});
});
console.log(count);
答案 1 :(得分:1)
答案 2 :(得分:0)
如果您知道具有projectid
属性的项目位于对象中的哪个位置,则可以执行以下操作:
var n = 0;
obj[0].bun.forEach(function(item){ if (item.projectid != null) n++});
如果不这样做,那就更复杂了。
答案 3 :(得分:0)
You can use a recursive function to find the occurrence of a key in the json
function walk(obj,keyname) {
var propertyCount=0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
if(typeof(val) == 'object') {
propertyCount += walk(val,keyname);
}else {
if(key == keyname){
propertyCount +=1;
}
}
}
}
return propertyCount;
}
alert(walk(obj,'projectid'));//obj is your json array
It will return 2