Specific number of keys in json jquery

I have json in that there will be a key that it can exist or not in jason data. Now I want to get the total key existence in jquery.

JSON:

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

How can we do this in jquery, please help me with this

+5
source share
4 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 compatibility with multiple browsers, 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> 
+6
source

No need for jQuery

This will give you an object showing each key and the number of times this happens.

 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); 
+1
source

This can also be done in the JS kernel ...

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

Make it very simple:

 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 number of keys and values ​​in any json array. Now customize this code according to your requirement, for example, increase and decrease the quantity or everything that you want to do.

Hope you have an approach !!!

0
source

All Articles