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
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
Share Improve this question asked Jun 11, 2015 at 10:24 Pooja DubeyPooja Dubey 6832 gold badges15 silver badges34 bronze badges 5- What is your expected result. – Madhu Magar Commented Jun 11, 2015 at 10:26
- @MadhuMagar three will be the total count as final result – Pooja Dubey Commented Jun 11, 2015 at 10:27
- @MadhuMagar i don't want to use foreach for this – Pooja Dubey Commented Jun 11, 2015 at 10:27
-
Just try
jasonData.length
– Sudharsan S Commented Jun 11, 2015 at 10:28 - @PoojaDubey can you show the sampe json output. – Madhu Magar Commented Jun 11, 2015 at 10:28
4 Answers
Reset to default 7You 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 patibility, 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./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);
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);
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 !!!