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. Am trying to implement in angular JS. Solutions in plain JS will also be helpful.
TIA
One approach is to use .filter()
on the object's keys:
var count = Object.keys(obj).filter(function (key) {
return key.indexOf(prefix) === 0;
}).length;
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
But actually it's not an array, it's a JSON object . And what we are counting is JSON key's.
JS Part:
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.
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/
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-"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.