What is the best way to tally the number of fields in a JSON file based on their values

I'm relatively new to JavaScript and have a question that may seem basic. I've been struggling to find the answer, possibly because I'm not using the correct terminology.

My goal is to count the number of "active" fields in a JSON file that are set to true versus false, and then store those values in a variable. I'm finding it challenging to figure out how to approach this task.

Here's an example of my JSON data, which I've named data:

{
"systems": [
    {
        "name": "SV001",
        "IP": "10.1.1.101",
        "active": "true"
    },
    {
        "name": "SV002",
        "IP": "10.1.1.102",
        "active": "true"
    },
    {
        "name": "SV003",
        "IP": "10.1.1.103",
        "active": "false"
    }
]}

I would greatly appreciate any assistance with this issue. Thank you!

Answer №1

To convert a JSON string into a JavaScript object, you can use the following code snippet:

var jsonObject = JSON.parse(jsonString);
Then, by traversing through the object using a loop, you can access its values.

var count = 0;
for (var i = 0; i < jsonObject.systems.length; i++) {
  if (jsonObject.systems[i].active) {
    count++;
  }
}

You will have the total count at the end of the loop.

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

a guide on extracting json data in android without using an array name

I have been attempting to parse a JSON result without an array name. Despite trying various methods, none of them seem to work with my code. Therefore, I am seeking guidance on how to parse the JSON result without using an array name. Thank you in advance ...

Implementing property filtering on a recursive self-reference with Jackson

Consider the scenario where I need to serialize a class using Jackson. public class Product { int id; String name; List<Product> similarProducts; } How can I achieve the desired JSON output like this? { "id": 1, "name": "Produc ...

Issue with bouncing dropdown menu

I am in the process of enhancing a Wordpress website by implementing a jQuery menu with sub-menus. Below is the jQuery code snippet: $(document).ready(function(){ $('.menu > li').hover(function(){ var position = $(this).position(); ...

When using Jackson's ObjectMapper to deserialize a JSON object, the method `readValue` returns an object with all fields

Currently, I am grappling with the challenge of deserializing a byte array into a Java type using Jackson object mapper. @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class A { String s; ...

Adjust positioning of navigation when hovered over

Need help creating a cool navigation effect like this. Live example: https://hookandbarrelrestaurant.com/ Here is my code: https://codepen.io/Dhaval182/pen/rQPMoW ...

What is the most effective Jackson converter for converting a Java DataHandler class to JSON?

I've developed a Spring REST service using spring-web 3. In my rest-servlet.xml, I have configured a Jackson converter as follows: <bean id="jackson2Converter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> ...

Insert well-formed JSON into an HTML element

I'm facing a challenge while trying to dynamically embed a valid JSON array into HTML. The issue arises when the text contains special characters like quotes, apostrophes, or others that require escaping. Let me illustrate the problem with an example ...

Showing every piece of information line by line while uploading an AJAX CSV file

I have successfully parsed a CSV file using Papaparse, Jquery AJAX, and PHP. Now, I want to display the data line by line while the CSV file is being uploaded. Here is a snippet of my code: var xhr_file = null; $('#fileVariants').change(functio ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

Convert HTML tables from Yahoo Pipes into an array of JSON objects

Currently, I am experimenting with Yahoo Pipes in an attempt to convert multiple tables within a DIV into an array of JSON objects. At the moment, the HTML is being successfully parsed. Here is my current setup on Yahoo Pipes I envision each table cell ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

What is the best way to utilize the .done() callback in order to execute a function when new data is loaded upon request?

I have a web page that pulls data from a JSON feed, and there's also a button to load more content from the feed when clicked. I want to add additional elements inside the page for each item in the feed. I've managed to create a function that doe ...

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...

Reading a CSV file using pandas, with the last column potentially containing commas

I am currently facing an issue with loading a well-formed CSV dataset using the pandas package. The header contains 5 column names and the final column consists of JSON objects with unescaped commas, like this: A,B,C,D,E 1,2,3,4,{K1:V1,K2:V2} When I try ...

What is the best way to execute JavaScript on the main MVC page when an AJAX request in a partial view has finished?

My Asp.net MVC partial view is designed for searching and makes an Ajax call to retrieve results. After the results are displayed, the user can select a search result by clicking on a link in one of the rows. Upon selecting a search result, an Ajax post re ...

Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function. function MapLocations() { var i = 0; var infoWindow = new google.map ...

Error encountered when attempting to embed a SoundCloud player in Angular 4: Unable to execute 'createPattern' on 'CanvasRenderingContext2D' due to the canvas width being 0

I attempted to integrate the SoundCloud iframe into my Angular 4 component, but encountered the following error message: Failed to execute 'createPattern' on 'CanvasRenderingContext2D': The canvas width is 0. Here is the iframe code ...

Exploring the contrast: resolve() versus fulfill() in q.js

I'm finding it difficult to understand the distinction between calling a resolver's resolve() as opposed to fulfill(). Both functions and terms "resolve a promise" and "fulfill a promise" are frequently used interchangeably. Can you provide guid ...

Refresh the div based on the script's output

Currently, I am struggling to make a password change form work properly as I have limited knowledge of jQuery. The form successfully changes the password, but there is no visual feedback for the user. When I submit the form, it routes to changePassword.php ...