Discovering the frequency of a specific key in a JSON object or array using JavaScript

Suppose I have a JSON object with the given data, how can I determine the frequency of the key: "StateID"?

[{"StateID":"42","State_name":"Badakhshan","CountryID":"1"},
{"StateID":"43","State_name":"Badgis","CountryID":"1"},
{"StateID":"44","State_name":"Baglan","CountryID":"1"},
{"StateID":"45","State_name":"Balkh","CountryID":"1"},
{"StateID":"46","State_name":"Bamiyan","CountryID":"1"},
{"StateID":"47","State_name":"Farah","CountryID":"1"},
{"StateID":"48","State_name":"Faryab","CountryID":"1"},
{"StateID":"49","State_name":"Gawr","CountryID":"1"},
{"StateID":"50","State_name":"Gazni","CountryID":"1"},
{"StateID":"51","State_name":"Herat","CountryID":"1"},
{"StateID":"52","State_name":"Hilmand","CountryID":"1"},
{"StateID":"53","State_name":"Jawzjan","CountryID":"1"},
{"StateID":"54","State_name":"Kabul","CountryID":"1"},
{"StateID":"55","State_name":"Kapisa","CountryID":"1"},
{"StateID":"56","State_name":"Khawst","CountryID":"1"},
{"StateID":"57","State_name":"Kunar","CountryID":"1"},
{"StateID":"58","State_name":"Lagman","CountryID":"1"},
{"StateID":"59","State_name":"Lawghar","CountryID":"1"},
{"StateID":"60","State_name":"Nangarhar","CountryID":"1"},
{"StateID":"61","State_name":"Nimruz","CountryID":"1"},
{"StateID":"62","State_name":"Nuristan","CountryID":"1"},
{"StateID":"63","State_name":"Paktika","CountryID":"1"},
{"StateID":"64","State_name":"Paktiya","CountryID":"1"},
{"StateID":"65","State_name":"Parwan","CountryID":"1"},
{"StateID":"66","State_name":"Qandahar","CountryID":"1"},
{"StateID":"67","State_name":"Qunduz","CountryID":"1"},
{"StateID":"68","State_name":"Samangan","CountryID":"1"},
{"StateID":"69","State_name":"Sar-e Pul","CountryID":"1"},
{"StateID":"70","State_name":"Takhar","CountryID":"1"},
{"StateID":"71","State_name":"Uruzgan","CountryID":"1"},
{"StateID":"72","State_name":"Wardag","CountryID":"1"},
{"StateID":"73","State_name":"Zabul","CountryID":"1"}]

Answer №1

If you want to achieve that, you can follow these steps:

let states = [{"StateID":"42","State_name":"Badakhshan","CountryID":"1"},{"StateID":"43","State_name":"Badgis","CountryID":"1"},{"StateID":"44","State_name":"Baglan","CountryID":"1"},{"StateID":"45","State_name":"Balkh","CountryID":"1"},{"StateID":"46","State_name":"Bamiyan","CountryID":"1"},{"StateID":"47","State_name":"Farah","CountryID":"1"},{"StateID":"48","State_name":"Faryab","CountryID":"1"},{"StateID":"49","State_name":"Gawr","CountryID":"1"},{"StateID":"50","State_name":"Gazni","CountryID":"1"},{"StateID":"51","State_name":"Herat","CountryID":"1"},{"StateID":"52","State_name":"Hilmand","CountryID":"1"},{"StateID":"53","State_name":"Jawzjan","CountryID":"1"},{"StateID":"54","State_name":"Kabul","CountryID":"1"},{"StateID":"55","State_name":"Kapisa","CountryID":"1"},{"StateID":"56","State_name":"Khawst","CountryID":"1"},{"StateID":"57","State_name":"Kunar","CountryID":"1"},{"StateID":"58","State_name":"Lagman","CountryID":"1"},{"StateID":"59","State_name":"Lawghar","CountryID":"1"},{"StateID":"60","State_name":"Nangarhar","CountryID":"1"},{"StateID":"61","State_name":"Nimruz","CountryID":"1"},{"StateID":"62","State_name":"Nuristan","CountryID":"1"},{"StateID":"63","State_name":"Paktika","CountryID":"1"},{"StateID":"64","State_name":"Paktiya","CountryID":"1"},{"StateID":"65","State_name":"Parwan","CountryID":"1"},{"StateID":"66","State_name":"Qandahar","CountryID":"1"},{"StateID":"67","State_name":"Qunduz","CountryID":"1"},{"StateID":"68","State_name":"Samangan","CountryID":"1"},{"StateID":"69","State_name":"Sar-e Pul","CountryID":"1"},{"StateID":"70","State_name":"Takhar","CountryID":"1"},{"StateID":"71","State_name":"Uruzgan","CountryID":"1"},{"StateID":"72","State_name":"Wardag","CountryID":"1"},{"StateID":"73","State_name":"Zabul","CountryID":"1"}]

let stateCount = states.reduce((countMap, state) => {
    countMap[state.StateID] = countMap[state.StateID] || 0;
    countMap[state.StateID]++;
    return countMap;
}, {});

console.log(stateCount);

Answer №2

To find the number of objects in an array that contain a specific property, you can utilize the filter method and return the count.

const
  data = [ {"StateID":"42","State_name":"Badakhshan","CountryID":"1"}, {"StateID":"43","State_name":"Badgis","CountryID":"1"}, {"StateID":"44","State_name":"Baglan","CountryID":"1"}, {"StateID":"45","State_name":"Balkh","CountryID":"1"}, {"StateID":"46","State_name":"Bamiyan","CountryID":"1"}, {"StateID":"47","State_name":"Farah","CountryID":"1"}, {"StateID":"48","State_name":"Faryab","CountryID":"1"}, {"StateID":"49","State_name":"Gawr","CountryID":"1"}, {"StateID":"50","State_name":"Gazni","CountryID":"1"}, {"StateID":"51...

/**
 * Determine how many items in the array have a specific property.
 *
 * @param {Array} dataset        The array to examine for the presence of 
 *                               the specified property.
 * @param {String} keyName       The name of the property to look for in 
 *                               the objects within the array.
 *
 * @returns {Number} The function returns the count of objects in the array 
 *                   containing the specified property.
 */
function calculateProperty(dataArr, keyName) {
  const
    targetItems = dataArr.filter(item => item[keyName] !== undefined);
    
  return targetItems.length;
}

console.log(`Count of "StateID" occurrences: ${calculateProperty(data, 'StateID')}`);

Answer №3

let count = 0;
for (let index=0; index < array.length; index++) {
if (array[index].stateId) {
count++;
}
}
console.log("number of items with stateId:", count);

Answer №4

Here's a potential example:

const myData = [your data];
console.log('Total count:', myData.filter(function(item){ return Object.keys(item).includes('StateID'); }).length);

Answer №5

There are several ways to achieve this goal, so feel free to explore other answers for alternative solutions.

This particular method uses an Array.prototype.forEach loop to check if the StateID is present and greater than 0.

data = [{"StateID":"42","State_name":"Badakhshan","CountryID":"1"},
{"StateID":"43","State_name":"Badgis","CountryID":"1"},
{"StateID":"44","State_name":"Baglan","CountryID":"1"},
// Additional state data goes here
{"StateID":"73","State_name":"Zabul","CountryID":"1"}];

var count = 0;
data.forEach(function(entry){
    entry.StateID > 0 ? count++ : null;
});
console.log(count);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Python script is functioning properly in Spyder and CMD, however it is encountering issues when run in Atom

I've encountered a coding issue with the following script: import requests import json url = 'https://www.protocols.io/api/v3/protocols?filter=%20public%20&order_field=relevance&key=%20gel%22electrophoresis%20' r = requests.get(ur ...

Tips on waiting for an event to be processed during a Protractor end-to-end test

I have a straightforward AngularJs 1.4.8 Front-End: https://i.stack.imgur.com/2H3In.png After filling out the form and clicking the OK button, a new person is added to the table. The form resides in the addingPersonController, while the table is control ...

Determine the presence of a number within a JSON string array that has been decoded in PHP

After successfully decoding my JSON string, I am now attempting to utilize the in_array() function in PHP to verify if ID number 5 exists within the array. Here is the Array: Array ( [0] => Array ( [id] => 5 ) [1] => Array ( [id] => 4 [childr ...

Any suggestions on how to address vulnerabilities in npm when upgrading the main dependency version is not an option?

I recently ran the npm audit --production command and found a high-risk vulnerability related to the snowflake-sdk dependency. After checking the snowflake github page, I noticed that the package.json file includes "requestretry": "^6.0.0&qu ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

Is there another way to retrieve a marketplace's product details using code?

When it comes to scraping products from various websites, I have discovered a clever method using window.runParams.data in the Chrome console. This allows me to easily access all the information without having to go through countless clicks to extract it f ...

What purpose does the next() function serve in Express.js?

Using this script to kickstart my next js app. I can't share the entire script, but I do need some assistance with the following: What is the purpose of compression? What is the importance of using helmet? What does next({dev}) do? const express = re ...

Sending data between Node.js middleware components

if (token_count == 1) { var user_name = rows[0].user_name; next(); } else { data = { message: "Invalid Token" } res.send(data); } I must pass the parameter user_name to function next(). When next() is called, it triggers the fo ...

Position the Bootstrap Modal at the start of the designated DIV

When using a Bootstrap Modal to display larger versions of thumbnails in a photo gallery, there can be some challenges. The default behavior of Bootstrap is to position the modal at the top of the viewport, which may work fine in most cases. However, if th ...

Connecting data with Ember CLI and ASP.NET WebAPI

I am facing an issue with integrating my Ember Cli project running on localhost:4200 and my asp.net webapi project running on localhost:56967. Both projects function properly individually: I can run my Ember app, test various routes, and access my api succ ...

Update the X-axis settings in Highcharts

Is it possible to pass an array from a PHP code to Highcharts? In the following PHP code, I create 4 arrays: TMax ($rows), TMin ($rows1), Rain ($rows2) for data and another one for days of consultation ($dia). $sth = mysqli_query($con,"SELEC ...

Identifying the presence of a period within a string

Forgive me for what may seem like a foolish inquiry, but I am unsure of how to search a string to determine if it includes a period. Here's what I have attempted: var text = "This is an example without a period. What next?" alert(text.search(".")); ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

Convert a list into a hierarchical structure of nested objects

Working with angular, I aim to display a nested tree structure of folders in an HTML format like below: <div id="tree"> <ul> <li ng-repeat='folder in folderList' ng-include="'/templates/tree-renderer.html'" ...

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

Splitting Angular modules into separate projects with identical configurations

My Angular project currently consists of approximately 20 different modules. Whenever there is a code change in one module, the entire project needs to be deployed. I am considering breaking down my modules into separate projects for individual deployment. ...

How can we show a varying number of textfields based on user selection using hooks and updating values dynamically through onChange events?

Currently, I am in the process of setting up a form that includes a Material UI select field ranging from 1 to 50. My challenge is how to dynamically display multiple textfields for "First Name and Last Name" using Hooks each time the user selects a number ...

Attempting to have the command "npm run dev" generate two separate shell instances

For my nuxt project, I decided to use json-server as the local server. My goal is to automate the process of launching the server and running the project on a separate shell instance by using the command "npm run dev". After some exploration, this is the ...