Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific key count in json jquery

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

like image 552
Pooja Dubey Avatar asked Jun 11 '15 10:06

Pooja Dubey


2 Answers

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>
like image 133
CodingIntrigue Avatar answered Nov 15 '22 09:11

CodingIntrigue


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);
like image 1
AmmarCSE Avatar answered Nov 15 '22 10:11

AmmarCSE