Determine the frequency of occurrences of a JSON property with a similar name

I am working on a Vue application that receives a JSON object as shown below. My task is to calculate the count of items where _Valid is set to true. I am not very familiar with the Reduce method in JavaScript and I'm unsure how to filter based on a specific part of a key name. Can someone guide me on where to start? Is this even achievable?

{
    "F_Mountain1_Week": "1",
    "F_Mountain1_Date": "2021-11-12",
    "F_Mountain1_Valid": true,
    "F_Mountain2_Week": "1",
    "F_Mountain2_Date": "2021-11-12",
    "F_Mountain2_Valid": true,
    "F_Mountain3_Week": "1",
    "F_Mountain3_Date": "2021-11-12",
    "F_Mountain3_Valid": true,
    "F_Mountain4_Week": "",
    "F_Mountain4_Date": "2021-11-12",
    "F_Mountain4_Valid": false,
    "F_Mountain5_Week": "",
    "F_Mountain5_Date": "2021-11-12",
    "F_Mountain5_Valid": false,
    "F_Mountain6_Week": "",
    "F_Mountain6_Date": "2021-11-12",
    "F_Mountain6_Valid": false,
    "F_Mountain7_Week": "",
    "F_Mountain7_Date": "2021-11-12",
    "F_Mountain7_Valid": false,
    "F_Mountain8_Week": "",
    "F_Mountain8_Date": "2021-11-12",
    "F_Mountain8_Valid": false,
}

Answer №1

This method can also be used

By utilizing the entries and filter functions. Initially, extract the key and value pairs from the data object and then apply a filter based on conditions involving the value and key attributes.

let information = {
    F_Mountain1_Week: "1",
    F_Mountain1_Date: "2021-11-12",
    F_Mountain1_Valid: true,
    // Rest of the data properties...
};

console.log(
    Object.entries(information).filter(([key, value]) =>  key.endsWith("_Valid") && value)
        .length
);

Answer №2

To iterate through the array and determine the count of properties that end with "_Valid" and have a value of true, you can utilize the reduce method like this:

Object.keys(obj).reduce((acc, curr) => curr.endsWith("_Valid") && obj[curr] ? acc + 1 : acc, 0)

Alternatively, you can achieve the same result using the filter method:

Object.keys(obj).filter((k) => k.endsWith("_Valid") && obj[k]).length;

const obj = {
  F_Mountain1_Week: "1",
  F_Mountain1_Date: "2021-11-12",
  F_Mountain1_Valid: true,
  F_Mountain2_Week: "1",
  F_Mountain2_Date: "2021-11-12",
  F_Mountain2_Valid: true,
  F_Mountain3_Week: "1",
  F_Mountain3_Date: "2021-11-12",
  F_Mountain3_Valid: true,
  F_Mountain4_Week: "",
  F_Mountain4_Date: "2021-11-12",
  F_Mountain4_Valid: false,
  F_Mountain5_Week: "",
  F_Mountain5_Date: "2021-11-12",
  F_Mountain5_Valid: false,
  F_Mountain6_Week: "",
  F_Mountain6_Date: "2021-11-12",
  F_Mountain6_Valid: false,
  F_Mountain7_Week: "",
  F_Mountain7_Date: "2021-11-12",
  F_Mountain7_Valid: false,
  F_Mountain8_Week: "",
  F_Mountain8_Date: "2021-11-12",
  F_Mountain8_Valid: false,
};

const result = Object.keys(obj).reduce((acc, curr) => curr.endsWith("_Valid") && obj[curr] ? acc + 1 : acc, 0);

console.log(result);

Answer №3

Traditional approach

let info = {
    F_Ocean1_Month: "1",
    F_Ocean1_Date: "2022-10-25",
    F_Ocean1_Valid: true,
    F_Ocean2_Month: "3",
    F_Ocean2_Date: "2022-12-07",
    F_Ocean2_Valid: false,
    F_Ocean3_Month: "5",
    F_Ocean3_Date: "2023-02-14",
    F_Ocean3_Valid: true,
    F_Ocean4_Month: "7",
    F_Ocean4_Date: "2023-04-01",
    F_Ocean4_Valid: false
};

for (var key in info) {
    if (typeof info[key] == 'function') continue;
    if(/_Valid$/.test(key) && info[key] === true) {
        console.log('SUCCESS!')
    } else {
        console.log('Irrelevant property:\n')
        console.log(`Key name: ${key} - Value: ${info[key]}`);
    }
}

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

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

Display popup just one time (magnific popup)

Attempting to display this popup only once during a user's visit. It seems like I might be overlooking something. <script src="http://code.jquery.com/jquery-1.7.min.js"> <link href="http://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1 ...

Challenge encountered while implementing a countdown using a for loop in a node.js application

I've been struggling with the following code and despite trying everything, I can't seem to find a solution. Hopefully, someone out there can lend me a hand. Currently, the code runs fRoll.roll, enters a FOR loop, initiates the countdown of the ...

Overflow-y SweetAlert Icon

Struggling with a website modification issue where using Swal.fire(...) causes an overflow problem affecting the icon rendering. How can this be fixed? Here is the custom CSS code in question: * { margin: 0px; padding: 0px; font-family: &ap ...

I discovered an issue in Handsontable while trying to copy and paste a numeric value in German format

For my upcoming project, I am looking to incorporate the Handsontable JavaScript grid framework. However, I have encountered a small bug that is hindering me from utilizing this library to its fullest potential. The task at hand involves displaying a tabl ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

Unable to input text by clicking using FabricJS combined with React and Jquery

I am currently working on a project using react and FabricJs. My goal is to add text to the fabricJS canvas by clicking on a button using jQuery. This is the code I have so far: import React, {Component} from 'react' import {fabric} from ' ...

Is it possible to integrate Firebase Storage into a TypeScript/HTML/CSS project without the use of Angular or React?

For my project, I am aiming to create a login and register page using TypeScript. Currently, my code is functioning well even without a database. However, I would like to implement Firebase for storing user credentials so that the login process becomes mor ...

Accessing stored web pages / Browser as an interactive interface

I have a couple of questions I need help with. The first one is about how to open a saved HTML file in a browser without an internet connection. Next, I'm looking for advice on using the browser as a user interface for a desktop image viewing program ...

Javascript if-else is malfunctioning

I am having difficulty running the code below which contains if statements. I have tried removing some parts of it, but still can't get the alert to show up. Any advice would be highly appreciated. Thank you. <!DOCTYPE html> &l ...

The slideToggle() function appears to be malfunctioning when sliding up or down, as it

Currently, I am in the process of creating a dropdown menu. However, I am facing an issue where the menu does not slide down or up smoothly when clicked. The animations seem to be delayed or non-existent. $('.menu-vertical .nav-menu > li'). ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Populate the textbox with data from the database when the dropdown selection changes

I am looking to automatically populate the text box with a value from the database when a selection is made from a drop-down list using php When an option is chosen from the drop-down list, the text box should display a corresponding record based on the s ...

Using Angular to invoke the transclude directive function inside the transcluded component

I am looking to develop a component that includes a transcluded section, take a look at this example: http://jsfiddle.net/vp2dnj65/1/ Upon clicking the "do" button in the example, nothing seems to happen. Is there a way to execute the transcluded cont ...

Updating a form field dynamically with AJAX in Laravel

I'm working on updating the field $medic->current based on certain logic that I have in mind. I'm quite new to using AJAX and would appreciate a little guidance to kick things off. In my code, I am calculating the difference between two dates ...

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

A guide to validating a pair of fields within a single object using React hooks and the Yup library

{ label: 'Room', name: 'room', rule: yup.array(yup.object()).required(), renderer: (data: any) => { const { control, register, errors } = useFormContext(); return ( ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

The $scope variable is missing from the DOM

I've been trying to implement ng-repeat with AngularJS, but I'm having trouble getting the scope result in my DOM. Is there something wrong that anyone can spot? I've spent hours troubleshooting this and no matter what I do, "players" always ...