Navigating through an object and dynamically inserting data using keys is a crucial skill to master

I've been delving into JavaScript objects lately.

1.

Units = [
    {
        "BedDetails": [
            {
                "Outpatient": 2,
                "ICU_Beds": 0,
                "NL_Beds": 2,
                "Extra": 9,
                "Ordinary": 3,
                "ADMIN": 6,
                "SVC_Areas": 3.2 // This is a different kind, not a type of bed
            }                  
        ]
    }, 
    {
        "BedDetails": [
            {
                "Outpatient": 4,
                "ICU_Beds": 2,                
                "Extra": 2,
                "Ordinary": 2,
                "ADMIN": 2,
                "SVC_Areas": 2.1 // This is a different kind, not a type of bed
            }
        ]
    }
]

Here are the three operations to perform:

  1. Sum by types of beds.
  2. If bed type > 0, then sum SVC_Areas as SVC_bedType.
  3. Ratio of Bed type / SVC_bedtype.

For example:

  • Step 1 sums up bed types.
  • Step 2 includes:

    If Outpatient > 0, then SVC_outpatient = 2.

    If ICU > 0, then SVC_ICU = 0 (since ICU = 0).

  • Step 3 calculates the ratio: `(sum of bedtype) / SVC_bedtype` obtained in Step 1/Step 2.

This is what I've done so far:

Units.forEach(function (element) {               
    var Beds_Details = element.BedDetails[0];                   
    Sum_Outpatient += Beds_Details.Outpatient;
    Sum_ICUBeds += Beds_Details.ICU_Beds;                   
    Sum_Extra += Beds_Details.Extra;
    Sum_Ordinary += Beds_Details.Ordinary;
    Sum_ADMIN += Beds_Details.ADMIN;

    if (Beds_Details.Outpatient > 0) { (SVC_Outpatient += Beds_Details.SVC_Areas).toFixed(2); }
    if (Beds_Details.ICU_Beds > 0) { (SVC_ICUBeds += Beds_Details.SVC_Areas).toFixed(2); }                    
    if (Beds_Details.Extra > 0) { (SVC_Extra += Beds_Details.SVC_Areas).toFixed(2); }
    if (Beds_Details.Ordinary > 0) { (SVC_Ordinary += Beds_Details.SVC_Areas).toFixed(2); }
    if (Beds_Details.ADMIN > 0) { (SVC_ADMIN += Beds_Details.SVC_Areas).toFixed(2); }
});

if (SVC_Outpatient > 0) { 
   RatioModel_Outpatient = (Sum_Outpatient / SVC_Outpatient).toFixed(2); 
} else { 
         RatioModel_Outpatient = 0; 
};

// Check other conditions and calculate ratios here...

The code works fine, but I'm looking to optimize it by looping through the Bed_details keys. Can anyone help with this?

Answer №1

Your specified requirements from our conversation have been successfully incorporated in the solution provided below. The final output will be available in the output object.

To view the operational example, please visit the following fiddle: AnswerFiddle

var output = {};
function calculatePropertySum(propertyName){
  var sum = 0;
  Units.forEach(function(obj){
      var item = obj.BedDetails["0"];
      sum =  sum + (item[propertyName]||0);
  });
  return sum;
};
function calculatePropertySVC(propertyName){
  var svc = 0;
  Units.forEach(function(obj){
    var item = obj.BedDetails["0"];
    if(item[propertyName]>0){
       svc = svc + (item.SVC_Areas||0);
    }
  });
  return parseFloat(svc.toFixed(2));
};

function getPropertyDetails(propertyName){
    var svc = calculatePropertySVC(propertyName);
    var sum = calculatePropertySum(propertyName);
    var ratio = svc === 0 ? 0: sum/svc;
    output["Sum_"+ propertyName] = sum;
    output["SVC_"+ propertyName] = svc;
    output["RatioModel_"+ propertyName] = parseFloat(ratio.toFixed(2));

}

var bedItem = Units[0].BedDetails[0];
for(var property in bedItem){
    if(property!=="SVC_Areas"){
            getPropertyDetails(property);
    }  
}
console.log(output);

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

Creating client side scripts for an ajax call to generate a Json object is simple once you understand the basics

Typically, when I make ajax calls, I request pure HTML. However, for various reasons, I require guidance on constructing a table (let's say of individuals and their information) when receiving a Json object. While I am capable of creating a table in J ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

When utilizing document.addEventListener in JavaScript, Firefox fails to report exceptions triggered by DOMContentLoaded

I'm developing an internal framework that must be independent of any external dependencies such as jQuery. I'm working on implementing a custom DOM ready-style functionality, where callbacks in the ready queue should continue executing even if an ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Ember.js: Issue with retrieving Binding property results in undefined value

The following code snippet is sourced from the official ember.js introduction: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> & ...

What is the best way to test a try/catch block within a useEffect hook?

Hey, I'm currently dealing with the following code snippet: useEffect(() => { try { if (prop1 && prop2) { callThisFunction() } else { callThatFunction() } ...

Using Vue.js, is it possible to apply a class to a clicked element and then remove it when another element is clicked?

While developing an app using Vue.js, I have run into an issue. I am familiar with how to solve this problem using jQuery, but I am struggling to find a solution within my Vue app. Let me explain quickly - I have a list of items and I want to assign a spec ...

Printing an array from JavaScript to an EJS template: Tips and Tricks

I'm currently working on a database-driven website that focuses on searching through people's profiles. When attempting to display information from a database query, I am encountering the issue of receiving [object Object]. Below are snippets o ...

Every 5 seconds, a message of "true" is sent. If the request does not reach the server within 10 seconds, how can a function be triggered?

For every 5 second interval, the client transmits the value "true". How can a function be triggered on the Node.js server if no request is received within a 10-second timeframe? Please provide an illustrative code example. Client: let time = JSON.stringi ...

Vue - Enhanced Image Cropper (Error: Unable to retrieve image result from this.$refs.cropper)

I have a crop function for Vue Advanced Cropper similar to the one below: crop() { const { canvas } = this.$refs.cropper.getResult(); if (canvas) { const form = new FormData(); canvas.toBl ...

Inquiries about JavaScript and the YouTube API

Being very resourceful, I am currently exploring ways to feature my YouTube links on my website in an elegant manner. Tired of the redundancy of posting on both platforms, I am seeking a solution that seamlessly integrates these posts. Despite my efforts, ...

What is the best way to refresh updated .js files directly from the browser console?

Is it possible to use RequireJS 2 to dynamically reload a recently updated .js file? Let me explain my scenario: I have a Backbone.js object named Foo with a function called Bar that currently displays an alert with "abc" when called; In my webpage, I ex ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

NUXT: Module node:fs not found

Encountering an error when running yarn generate in a Kubernetes container during production. The same command works fine locally and was also functioning properly in production up until last week. Error: Cannot find module 'node:fs' Require stac ...

Finding an Element by its Class Name

Can someone assist me in selecting an element using its class name? I currently have GWT 2.0 and I am trying to accomplish this. Your help would be greatly appreciated. Thank you ...

Error in ThreeJS: Unexpected data type for Orbit Controls - b[c].call is not a valid function

I have been working on a three.js project and have successfully implemented orbit controls. However, I am encountering an error where for every single pixel I move my mouse over, the following error is thrown: Uncaught TypeError: b[c].call is not a functi ...

Sender receives a response from Socket.io

My goal is to have a socket respond only to the sender. Currently, I am working on having the user connect to the server using JavaScript when they visit any webpage. However, I am unsure whether the connection will be reset each time the user reloads th ...

Using Angular 1.4 - How to utilize a single controller with $routeProvider

How can I use the same controller on both full and mobile views using $routeProvider? The code below does not work as expected. What am I missing? Alternatively, is it possible to have the same controller but with different templateUrl based on the user a ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...