I have a json in that there will be key it can exists or not in the jason data .Now what i want to get total number of existence of the key in jquery.
JSON :
jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
How can we do this in jquery please help me in this
You can use filter for this:
var jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
var count = jasonData.filter(function(element) {
return element.test;
}).length;
document.write(count);
Or, for further cross-browser compatibility, jQuery provides a similar grep function:
var jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
var count = $.grep(jasonData, function(element) {
return element.test;
}).length;
document.write(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No jQuery needed
This will give you an object showing each key and the number of times it occurs
var jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
var keyCounts = {};
for (var i = 0; i < jasonData.length; i++) {
var key = Object.keys(jasonData[i])[0];
if (typeof(keyCounts[key]) == 'undefined') {
keyCounts[key] = 1;
} else {
keyCounts[key] += 1;
}
}
console.log(keyCounts);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With