Pooja Dubey
Pooja Dubey

Reputation: 683

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

Upvotes: 6

Views: 1878

Answers (4)

Sunil Sharma
Sunil Sharma

Reputation: 1315

Do it in a very simple way ::

var tempArr = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
var tempObj;

for(var i=0;i<tempArr.length;i++){
    tempObj = tempArr[i];
    for(key in tempObj){
        alert("key : "+key +"value  : "+tempObj[key]);
    }
}

This way you can get any no of keys and values in any json array. Now tweak this code according to your requirement like increase and decrease the count or whatever you want to do.

Hope you got the approach !!!

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30557

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);

Upvotes: 1

Ashish_B
Ashish_B

Reputation: 114

This can be done in core JS as well...

Here is the running code.

var jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}];
var sum=0;
jasonData.forEach(function(value,i){
  if(value.test){
    sum++;  
  }
});
console.log(sum);

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78535

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>

Upvotes: 7

Related Questions