[英]Counting occurrences of Javascript array indexes
I have the following array. 我有以下数组。
"APP-A": {
"active": true
},
"APP-B": {
"active": true
},
"APP-C": {
"active": true
},
"BOOL-A": {
"active": true
},
"BOOL-B": {
"active": true
},
"BOOL-C": {
"active": true
},
I need to get the total count of the APP-*'s in the array. 我需要获取数组中APP- *的总数。 Am trying to implement in angular JS.
我正在尝试在有角JS中实现。 Solutions in plain JS will also be helpful.
普通JS中的解决方案也将有所帮助。
TIA TIA
One approach is to use .filter()
on the object's keys: 一种方法是在对象的键上使用
.filter()
:
var count = Object.keys(obj).filter(function (key) {
return key.indexOf(prefix) === 0;
}).length;
http://jsfiddle.net/4m692usx/1/ http://jsfiddle.net/4m692usx/1/
may be try like this: 可以这样尝试:
var items = { "APP-A": {
"active": true
},
"APP-B": {
"active": true
},
"APP-C": {
"active": true
},
"BOOL-A": {
"active": true
},
"BOOL-B": {
"active": true
},
"BOOL-C": {
"active": true
}
};
var c=0;
for(var item in items)
{
if(item.indexOf("APP-") >= 0)
c++;
}
console.log(c);// your count here.
Check this JSFiddle Link
检查此
JSFiddle Link
But actually it's not an array, it's a JSON object . 但实际上它不是数组,而是JSON对象 。 And what we are counting is JSON key's.
我们正在计算的是JSON键。
JS Part: JS部分:
var items = { "APP-A": {
"active": true
},
"APP-B": {
"active": true
},
"APP-C": {
"active": true
},
"BOOL-A": {
"active": true
},
"BOOL-B": {
"active": true
},
"BOOL-C": {
"active": true
}
};
var app_count = 0;
for(var ik in items) {
if(ik.indexOf("APP-") >= 0) {
app_count++;
}
}
alert(app_count);
console.log(app_count);
var myArray = { "APP-A": { "active": true }, "APP-B": { "active": true }, "APP-C": { "active": true }, "BOOL-A": { "active": true }, "BOOL-B": { "active": true }, "BOOL-C": { "active": true } }; var reg = /^APP-/, count = 0, name; for (name in myArray) { count += reg.test(name); } document.getElementById('output').innerHTML = count;
<div id="output"></div>
That looks like a json, not an array. 看起来像json,而不是数组。
var count = 0;
for (var key in json) {
key.indexOf('APP-')!==-1?count++,count;
}
You can do something like this. 你可以做这样的事情。
http://jsfiddle.net/098o3kch/1/ http://jsfiddle.net/098o3kch/1/
var items = { "APP-A": {
"active": true
},
"APP-B": {
"active": true
},
"APP-C": {
"active": true
},
"BOOL-A": {
"active": true
},
"BOOL-B": {
"active": true
},
"BOOL-C": {
"active": true
}
};
function getCount(obj,pattern){
var cnt = 0;
for(var item in obj)
{
if(item.indexOf(pattern) >= 0)
cnt++;
}
return cnt;
}
alert(getCount(items, "APP-"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.