Navigating through JavaScript object and tallying the occurrences

How do I iterate through the properties of a JavaScript object and count the occurrences of a specific value?

    angular.module('App',[])
        .controller('mainCtrl', ['$scope', function ($scope) {

           var data = {  
   "plans":[  
      {  
         "id":1,
         "code":"NEXT_DAY_500gm",
         "name":"Next Day less than 500gm",
         "cost":55,
         "duration":24,
         "min_weight":0,
         "max_weight":500,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      },
      {  
         "id":2,
         "code":"NEXT_DAY_500gm_1kg",
         "name":"Next Day 500gm to 1kg",
         "cost":70,
         "duration":24,
         "min_weight":501,
         "max_weight":1000,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      },
      {  
         "id":3,
         "code":"NEXT_DAY_1kg_2kg",
         "name":"Next Day 1kg to 2kg",
         "cost":95,
         "duration":24,
         "min_weight":1001,
         "max_weight":2000,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      },
      {  
         "id":4,
         "code":"SAME_DAY_500gm",
         "name":"Same Day less than 500gm",
         "cost":95,
         "duration":8,
         "min_weight":0,
         "max_weight":500,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      },
      {  
         "id":5,
         "code":"SAME_DAY_500gm_1kg",
         "name":"Same Day 500gm to 1kg",
         "cost":130,
         "duration":8,
         "min_weight":501,
         "max_weight":1000,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      },
      {  
         "id":6,
         "code":"SAME_DAY_1kg_2kg",
         "name":"Same Day 1kg to 2kg",
         "cost":165,
         "duration":8,
         "min_weight":1001,
         "max_weight":2000,
         "COD":1,
         "created_at":"-0001-11-30 00:00:00",
         "updated_at":"-0001-11-30 00:00:00"
      }
   ]
};  
          $scope.data1=data;       
       }]);

I am looking to tally the number of times the "status" field is marked as "COMPLETE" in order to assign that count to a variable. For instance, if "COMPLETE" appears 4 times, my sale variable will be set to 4. Any suggestions on how to achieve this?

Answer №1

To achieve the desired result, it is essential to implement a filter function in this situation:

let completedTasks = data.filter(function(task) {
    return task.status === 'COMPLETED';
}).length;

console.log(completedTasks);

Answer №2

The purpose of the forEach() method is to run a specified function for each element in an array.

var data = [{
  "id": 23,
  "sender_id": 3,
  "courier_id": 0,
  "deliverer_id": 0,
  "status": "PENDING",
  "consignment_id": "55C0A999",
  "sender_name": "asdasdas d",
  "cost": "40",
  "package_description": "asdasdasd",
  "sender_address": "asdasdasd",
  "sender_longitude": "",
  "sender_latitude": "",
  "sender_number": null,
  "receiver_address": "adasdasd",
  "receiver_name": "Shifat Adnan",
  "receiver_number": "01713206053",
  "receiver_longitude": "",
  "receiver_latitude": "",
  "current_longitude": "",
  "current_latitude": "",
  "deliverer": null,
  "recipient_pays": 0,
  "instructions": "2332323",
  "payment_status": null,
  "cod": 0,
  "recipient_zone_id": 2,
  "plan_id": 2,
  "store_id": null,
  "storeproduct_id": null,
  "created_at": "2015-08-04 12:01:29"
}, {
  "id": 28,
  "sender_id": 5,
  "courier_id": 0,
  "deliverer_id": 0,
  "status": "COMPLETED",
  "consignment_id": "10F317",
  "sender_name": "bleh",
  "cost": "398",
  "package_description": "Business Order",
  "sender_address": "bleh",
  "sender_longitude": "bleh",
  "sender_latitude": "bleh",
  "sender_number": "bleh",
  "receiver_address": "kjakdjlsdjlaksdjl",
  "receiver_name": "Nigga",
  "receiver_number": "010203001",
  "receiver_longitude": "",
  "receiver_latitude": "",
  "current_longitude": "bleh",
  "current_latitude": "bleh",
  "deliverer": null,
  "recipient_pays": 0,
  "instructions": "jslklsdflkj",
  "payment_status": null,
  "cod": 0,
  "recipient_zone_id": null,
  "plan_id": 4,
  "store_id": null,
  "storeproduct_id": null,
  "created_at": "2015-10-04 09:36:23"
}, {
  "id": 34,
  "sender_id": 5,
  "courier_id": 0,
  "deliverer_id": 0,
  "status": "PENDING",
  "consignment_id": "137F24",
  "sender_name": "bleh",
  "cost": "3223",
  "package_description": "Business Order",
  "sender_address": "bleh",
  "sender_longitude": "bleh",
  "sender_latitude": "bleh",
  "sender_number": "bleh",
  "receiver_address": "kasdlkaskd asldka",
  "receiver_name": "FAAskl",
  "receiver_number": "199102909",
  "receiver_longitude": "",
  "receiver_latitude": "",
  "current_longitude": "bleh",
  "current_latitude": "bleh",
  "deliverer": null,
  "recipient_pays": 0,
  "instructions": "dsdsdf",
  "payment_status": null,
  "cod": 0,
  "recipient_zone_id": 2,
  "plan_id": 3,
  "store_id": null,
  "storeproduct_id": null,
  "created_at": "2015-10-06 07:58:28"
}, {
  "id": 35,
  "sender_id": 5,
  "courier_id": 0,
  "deliverer_id": 0,
  "status": "COMPLETED",
  "consignment_id": "13C476",
  "sender_name": "bleh",
  "cost": "3310",
  "package_description": "Business Order",
  "sender_address": "bleh",
  "sender_longitude": "bleh",
  "sender_latitude": "bleh",
  "sender_number": "bleh",
  "receiver_address": "sdfs dfasdfasdfasdf",
  "receiver_name": "sfasd",
  "receiver_number": "224",
  "receiver_longitude": "",
  "receiver_latitude": "",
  "current_longitude": "bleh",
  "current_latitude": "bleh",
  "deliverer": null,
  "recipient_pays": 0,
  "instructions": "dasdasd",
  "payment_status": null,
  "cod": 0,
  "recipient_zone_id": 2,
  "plan_id": 1,
  "store_id": 1,
  "storeproduct_id": 1,
  "created_at": "2015-10-06 12:54:14"
}, {
  "id": 36,
  "sender_id": 5,
  "courier_id": 0,
  "deliverer_id": 0,
  "status": "COMPLETED",
  "consignment_id": "13C4B3",
  "sender_name": "bleh",
  "cost": "330",
  "package_description": "Business Order",
  "sender_address": "bleh",
  "sender_longitude": "bleh",
  "sender_latitude": "bleh",
  "sender_number": "bleh",
  "receiver_address": "sdfs dfasdfasdfasdf",
  "receiver_name": "Some full name",
  "receiver_number": "224",
  "receiver_longitude": "",
  "receiver_latitude": "",
  "current_longitude": "bleh",
  "current_latitude": "bleh",
  "deliverer": null,
  "recipient_pays": 0,
  "instructions": "dasdasd",
  "payment_status": null,
  "cod": 0,
  "recipient_zone_id": 3,
  "plan_id": 4,
  "store_id": 1,
  "storeproduct_id": 2,
  "created_at": "2015-10-06 12:55:15"
}];
var count = 0;
data.forEach(function(item) {
  if (item.status === 'COMPLETED') {
    ++count;
  }
});
alert(count);

Answer №3

To iterate through your json object, use the following code snippet:

var totalComplete = 0;
for(var index = 0; index < jsonData.length; index++) {
    var item = jsonData[index];
    if (item['status'] == "COMPLETE"){
        totalComplete += 1;
    }
}
//perform actions using totalComplete.

Answer №4

    let total = 0;

    for (let index = 0, length = data.plans.length; index < length; index++)
    {
        if (data.plans[index].status === 'COMPLETE')
        {
            total++;
        }
    }

    if (total === 4)
    {

    }

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

Tips for updating an array in TypeScript with React:

Encountering an issue while updating my state on form submission in TypeScript. I am a newcomer to TS and struggling to resolve the error. enum ServiceTypeEnum { Replace = 'replace product', Fix = 'fix product', } interface IProduc ...

The Ajax code fails to refresh the document object model

I've encountered a small issue with my Ajax script that performs a POST request and displays the result on the screen. Even though the POST request is successful, I'm not able to view the result on the screen. It seems like there might be a need ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

Guidelines for naming classes in scss when working with Next.js

Is it possible to use CSS naming conventions in SCSS files with Next.js and then import them into JavaScript using a different convention? // login.module.scss file: .login-button { // some scss styling } // Login.js file: import styles from './ ...

Utilizing JavaScript to dynamically adjust the height of one div to match the height of another div

Struggling to adjust the height of one div to match another using the following code: var aboutheight=document.getElementById('about').offsetHeight; document.getElementById('sampledogs').setAttribute("style","height:aboutheight"); Des ...

Is it possible to generate .js, .min.js, and .js.map files using gulp?

My goal is to minify my resource files using gulp 3.9. I have set up two tasks in my gulpfile as follows: var gulp = require("gulp"), concat = require("gulp-concat"), cssmin = require("gulp-cssmin"), filter = require('gulp-filter'), sourcemaps ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

JavaScript event/Rails app encounters surprising outcome

I have encountered a strange bug in my JavaScript code. When I translate the page to another language by clicking on "English | Русский" using simple I18n translation, my menu buttons stop working until I reload the page. I suspect that the issue ...

How to utilize JSON for decoding information in PHP

I am in need of decoding this Json using PHP, but I am not sure how to do it. I have looked at the function on php.net/json, but it does not provide instructions on how to decode this specific type of data. {"c":[{"v":"0","e":"","n":"45","cc":"PSDB - PT ...

Why does node.js struggle to find other TypeScript React components?

Currently, I am in the process of converting some react server-side rendering files to typescript. However, I have encountered an issue with locating my custom components. The file path structure is as follows: node_modules/ src/ page/Homepage.tsx ...

A guide on utilizing ClassName to insert new items into a DIV

Original HTML code: <span class="specLink"> <specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty> </span> <br /> <span class="specLink"> <specialty2><a titl ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

eBay API request error: "You do not have the necessary permissions to complete the request."

While working on integrating the eBay API, I encountered an issue with creating a payment policy. Following the instructions provided in this guide , I generated a token and sent it using Postman. However, I received an error: { "errors": [ ...

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

What strategies are available for managing intricate nested data conversions in TypeScript with lodash?

I am currently developing a TypeScript project that involves performing intricate transformations on deeply nested JSON data. While I am utilizing lodash for utility functions, I have encountered a challenge in the following scenario: { "users" ...

Navigating with router.push in Vue.js to the same path but with different query parameters

The existing URL is /?type=1 I am attempting to implement router.push on this specific page. this.$router.push('/?type=2'); However, it results in a NavigationDuplicated error. I prefer not to utilize parameters such as /:type ...

Update the jQuery script tag with new content - rewrite everything

I am facing an issue with jquery. I need to change the link to src only when "document.write" is present. Below is my code: myscript.js document.write("TEST ABCD"); test.html <html> <body> <button id="example">click me</button&g ...

Swaying while navigating through volumetric fixed step raymarching

Encountering a bug with my shaders while working on the vertex: varying vec3 worldPosition; varying vec3 viewDirection; void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); worldPosition = vec3(modelMatrix * vec4 ...

Tips for switching the status of each item as I navigate the page with the tab key

I am facing an issue with my list of items that have hidden content appearing on hover. I want to achieve the same functionality while tabbing through my page, but currently, all hidden content appears at once. Check out a live example of my code here jQ ...

Retrieve the keys stored within a complex array of objects

I am searching for a function that can transform my data, specifically an array of objects with nested objects. The function should only include keys with immediate string/number/boolean values and exclude keys with object/array values. For example: [ { ...