Discovering the worth of an array property in JavaScript

I have a custom script that generates and outputs a JSON formatted object:

function test() {
    autoscaling.describeAutoScalingGroups(params, function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else console.log(JSON.stringify(data)); // successful response
    });
}

test();

The resulting JSON content is as follows:

{
  "ResponseMetadata": {
    "RequestId": "##################"
  },
  "AutoScalingGroups": [
    {
      "AutoScalingGroupName": "################",
      "AutoScalingGroupARN": "arn:aws:autoscaling:eu-west-1:#########:autoScalingGroup:###########",
      "LaunchConfigurationName": "######-LC-###########",
      "MinSize": 0,
      "MaxSize": 0,
      "DesiredCapacity": 0,
      "DefaultCooldown": 300,
      "AvailabilityZones": [
        "eu-west-1b",
        "eu-west-1c",
        "eu-west-1a"
      ],
      "LoadBalancerNames": [
        "#########-ELB-###########"
      ],
      "TargetGroupARNs": [

      ],
      "HealthCheckType": "ELB",
      "HealthCheckGracePeriod": 300,
      "Instances": [

      ],
      "CreatedTime": "2017-11-08T18:22:05.093Z",
      "SuspendedProcesses": [
        {
          "ProcessName": "Terminate",
          "SuspensionReason": "User suspended at 2017-11-08T18:22:14Z"
        }
      ],
      "VPCZoneIdentifier": "subnet-######,subnet-#######,subnet-#######",
      "EnabledMetrics": [

      ],
      "Tags": [
        {
          "ResourceId": "#######-ASG-##########",
          "ResourceType": "auto-scaling-group",
          "Key": "aws:cloudformation:logical-id",
          "Value": "ASG",
          "PropagateAtLaunch": true
        },
        {
          "ResourceId": "#######-ASG-#########",
          "ResourceType": "auto-scaling-group",
          "Key": "aws:cloudformation:stack-id",
          "Value": "arn:aws:cloudformation:eu-west-1:########:stack/##############",
          "PropagateAtLaunch": true
        },
        {
          "ResourceId": "################",
          "ResourceType": "auto-scaling-group",
          "Key": "aws:cloudformation:stack-name",
          "Value": "#######",
          "PropagateAtLaunch": true
        }
      ],
      "TerminationPolicies": [
        "Default"
      ],
      "NewInstancesProtectedFromScaleIn": false
    }
  ]
}

I am seeking to extract the value of

"SuspendedProcesses":[{"ProcessName"
: (refer above)

If the value of "ProcessName" == "Terminate" (as seen above), I want to execute one set of instructions; otherwise, another.

I understand how to structure the if-else statement, but I'm unsure about obtaining the value of "ProcessName" from the JSON output in advance.

While I confidently handle arrays created within a script, I'm encountering difficulty in this context because the JSON object is generated by the test() function, so conventional rules seem not to apply.

Your guidance on this matter would be greatly appreciated. Thank you.

Answer №1

To enhance your code, start by replacing console.log() statements with return statements. This will allow you to simplify the code as shown below:

var jsonData = fetchData();
var processes = jsonData["AutoScalingGroups"][0]["Suspended Processes"];

Here is the updated version of your code:

function fetchData() { 
    autoscaling.describeAutoScalingGroups(params, function(err, data) { 
        if (err) {
            return [err, err.stack]; // Handle error occurrence
        } else {
            var json = JSON.stringify(data);
            return json["AutoScalingGroups"][0]["Suspended Processes"];
        }
    }); 
} 

var processes = fetchData(); 
console.log(processes); 

Answer №2

hey @RobbieMilejczak, problem sorted:

To fix the issue, start by replacing all console.log() calls with return statements. Then proceed to execute

var jsonData = getTestData();
var services = jsonData["AutoScalingGroups"][0]["Suspended Processes"]
updated snippet:

function getTestData() { 
    autoscaling.describeAutoScalingGroups(params, function(error, response) { 
        if (error) {
            return [error, error.stack]; // an error occurred 
        } else {
            var jsonData = JSON.stringify(response); // successful response 
            return jsonData["AutoScalingGroups"][0]["Suspended Processes"];
        }
    }); 
} 
var services = getTestData()
console.log(services); 

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

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...

Embed the website onto a webpage using ajax or an iframe without any need for navigation

I have a unique challenge ahead. Imagine there are two websites, one is a web page and the other is hosted within the same domain. My goal is to load the entire second website into a div or iframe of the first web page, similar to how a free proxy browser ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Adding items to an array retrieved from JSON

My goal is to merge 3 different Facebook feeds into a single object called "item." Each item includes the post creation time and the JSON data itself. However, I'm facing an issue where only 5 items are displayed when I check the log, even though ther ...

The values in my array are causing it to output NAN

I'm currently working on a program that aims to combine a variable number of one-row matrices with varying lengths. The goal is to add the elements of each matrix together, where element one of array one adds to element one of array two, and so forth. ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

Error in React Material UI: 'theme' variable is not defined - no-undef

In the process of developing a basic React application with material-ui, I am incorporating MuiThemeProvider and ThemeProvider for themes. App.js import React from 'react'; import { createMuiTheme, MuiThemeProvider } from '@material-ui/co ...

Show the Canvas element at the back of the DIV

This particular question requires a clear explanation. My goal is to have the canvas act as a background element on the page, while the main content of the page starts in its usual position. I attempted using separate DIVs with their own Z-index values, bu ...

Bring to the front the div altered by a CSS3 animation

Recently, I encountered an issue with a div card that triggers an animation when clicked. The animation involves the card scaling up larger, but the problem arises as its edges get hidden under other cards. To visualize this, take a look at the screenshot ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

Retrieve an array of information from a firestore database query

I am encountering an issue while trying to retrieve information about all users who are friends of a specific user. I have attempted to gather the data by pushing it to an array and then returning it as a single JSON array. However, it seems that the dat ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Obtain image URL from object properties using AngularJS

Just starting out with Angular JS and I have a question. I'm currently working on a project and I have a solution in mind, but I was wondering if there's a more "angular-esque" approach that I could take. The idea is for each videoid, there wou ...

Modify the values of an object by utilizing the setter function

How can I utilize the setter method to update existing values of an object and perform mathematical operations? var obj = { set model(object) { //method's logic } }; obj = {x:10, y: 20, p: 15}; obj = { x:10, y: 20, p: 15 set mod ...

Utilizing Redux Reselect for Comment Filtering

Currently, I am attempting to filter and showcase comments that have a matching 'postID' with the current post id. Utilizing Redux/Reselect, the functionality works well but occasionally an error pops up indicating that post._id is undefined/null ...

Choose all the alternative A radio buttons utilizing JavaScript

If the "4 stars" option is selected at the top, I want all corresponding "4 stars" options in the form to be automatically selected. Similarly, if "3 stars" is chosen, I need all the "3 stars" options to be selected. I attempted to achieve this functionali ...

Setting the height of Material-UI TreeView

Looking for advice on how to set a fixed height or dynamically adjust the height of a material-ui TreeView to fit the display? I'd like a scrollbar to appear when the TreeView content reaches a height of 100 pixels, for example, or fills 100% of the ...

JavaScript visibility disappearing intermittently

I have created a custom image viewer box that overlays a thumbnail gallery page. The image viewer should appear when a user clicks on a thumbnail. However, currently, the viewer only pops up briefly and then disappears again. I am looking for a way to mak ...