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

Retrieve the content of a different page and store it as a variable using ajax

Is it possible to assign the content of another HTML page to a JavaScript variable? I attempted: var X = $(http://www.website.com/home).html() Unfortunately, this did not work, even though it seemed like a good idea. Can anyone provide guidance on how t ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

Enabling the apple-mobile-web-app-capable feature prevents SVG touches from registering

Looking to enhance touch functionality on an SVG element. The touch event detection is done using a jQuery-like selector. (Currently utilizing angular JQLite - angular.element()): .on("mousedown touch", function(event) { No problems with recognition of ...

What is the best way to update these respond_to options for Rails 3?

generate_response do |customization| if @user.valid? customization.js { generate_custom_response :none => true, :result_status => :ok, :address_to => @user } else customization.js { generate_custom_response :json => @user.errors, :r ...

Iterate through JSON objects in a loop and incorporate the results of a shell command to include a new

I am currently working on iterating over a JSON structure and adding a new field to each object within the JSON. Although, I am implementing this process within a stage of a Gitlab pipeline, I believe that detail is not crucial. Here is the JSON structure ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

What is the proper way to serialize JSON using GSON on Android?

How can I correctly serialize this JSON using GSON on Android? [ { "id": "bitcoin", "name": "Bitcoin", "symbol": "BTC", "rank": "1", "price_usd": "15022.7", "price_btc" ...

Exploring the possibilities of using React for looping?

I have integrated Dexie.js with React for this specific example. However, the implementation details are not of great importance to me. My main focus is on finding out how to iterate through all objects in my IndexDB database using React. In the code snip ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

What is the best way to encode the result from an object response into JSON format

I need to return JSON from a PHP API processor script and handle error messaging. Here is how I am currently doing it: try { $tax = $client->taxForOrder([ "field"=>($value), "field"=>($value), //etc ); $data = $ ...

Adding images sourced from the News API

I have successfully integrated an API from newsapi.org, and it's functioning well. However, the data I receive is only in text format and I would like to include images for each headline. I'm unsure of how to do this since the headlines are dynam ...

Taking a Symfony approach to handling actions that return a JSON response

Utilizing PHP and CURL, I am retrieving data from a server in one of my actions and then returning the data in JSON format. The code for my action is as follows: public function executeTest(sfWebRequest $request) { $json = $this->getServerResponse ...

Using a set formatter in jqGrid within a personalized formatter

Can I incorporate a predefined formatter into a custom formatter? Here is an example using the colModel: colModel: [ ... { name: 'col1', formatter: myFormatter } ... ] Below is the custom formatter function: function myFormatter(cellVal ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Perform a search within an iframe

Despite the fact that iframes are considered outdated, I am attempting to create a browser within an HTML browser. I have implemented a search bar that opens the typed input in a new window which searches Google. However, I would like to modify it so that ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Leveraging jQuery to extract the value from a concealed form field

Seeking assistance with a jQuery issue... I am attempting to use jQuery to retrieve the values of hidden fields in a form. The problem I am facing is that there are multiple forms displayed on the same page (result set items for updating), and the jQuery ...

Node.js middleware for verifying required parameters

In my current application, I am utilizing node.js and express. I have developed multiple middleware functions, each one created in a similar fashion: function loadUser(req, res, next){ ... } I am interested in creating a middleware that can validate th ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

Is it true that the Haskell Text.Json library is capable of reading Rationals but not writing them?

After attempting to parse a JSON file containing a floating point number, I noticed that the Text.JSON package returns the number as a JSRational. This means I can use readJSON on a JSRational. However, I encountered an issue when trying to write rationa ...