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

What steps can I take to resolve the spawn unknown error when using npx create-next-app in Visual Studio Code (VSCode)?

Every time I attempt to create a new app using either vscode or cmd, I encounter a spawn unknown error. The error message says "Aborting installation. Unexpected error. Please report it as a bug: Error: spawn UNKNOWN". Unfortunately, the installation abo ...

Using Node.js and Express to retrieve data from a MySQL database and update a table

My .ejs file contains a form that sends data to a MySQL database and then displays two tables with the retrieved data on the same page. However, I am facing an issue where the tables do not refresh after submitting the form, requiring me to restart the ser ...

Using Ruby on Rails to handle a POST request from an Android application

After developing a small RoR project using devise and scaffolding, I encountered an issue when registering new users. The result on my desktop differs from the result on my android app that uses JSON. Below is a snippet of the source code from the desktop ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

Is there a problem with addEventListener returning false?

What does keeping the third parameter as false in the line below signify? var el = document.getElementById("outside"); el.addEventListener("click", modifyText, false); ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

Exploring External Functions in Angular Beyond the Library

Transitioning from standard JavaScript to Angular has been a bit challenging for me, especially when working with the Google Places library (or any other asynchronous callback). Here is the code snippet: var sparkApp = angular.module('sparkApp' ...

JQuery appended Bootstrap Modal to Body, but it refuses to close

After going through the process of appending the modal to the body and getting the text box working, I encountered an issue when trying to close it on the AJAX success event - none of my attempted solutions seem to be effective. var id; var refundAmount ...

Struggling with Implementing jQuery for Triggering Multiple Functions on a Single Change Event?

I am currently developing jQuery functions that create dependencies between the css classes of different inputs in a web form. For example, when a specific input has a certain value, the "hide" class is removed from another input. One working example of t ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Requesting Access-Control-Request-Headers using jQuery Ajax POST method

I am attempting to send an AJAX request to my server. Initially, I referenced a library (in the web) within a <script> tag in my HTML document and executed it using the following code: $.ajax({ url: api_url + "movie/create", type : "POST", con ...

Launching a React project using the terminal - my step-by-step process

I'm attempting to initiate a new react-app utilizing the command npx create-react-app <app name> as shown below: npx create-react-app new-app However, after downloading, it seems to be stuck. It's not progressing at all. I've even rei ...

A comprehensive guide on associating a JavaScript function with an element attribute

I am looking for a way to assign a JavaScript function to an HTML attribute. For example: <li data-ng-repeat="job in jobList" class= dynamicClass(str) data-filter = "dynamicFilter(str)"> The reason I want to do this is because the class name and ...

Checkbox enabled Bootstrap image

I am encountering a minor issue where I am attempting to incorporate a simple image that can be toggled on and off by clicking on it. After coming across some bootstrap code online, I decided to test it in my project. Unfortunately, the code does not seem ...

Expanding upon passing arguments in JavaScript

function NewModel(client, collection) { this.client = client; this.collection = collection; }; NewModel.prototype = { constructor: NewModel, connectClient: function(callback) { this.client.open(callback); }, getSpecificCollection: ...

Issue with Angular-cli: typescript files not being generated when using the --dev option

Currently using angular-cli version 1.0.0-beta.14 with node version 6.6.0 on a Windows 32 bit x64 operating system. This setup utilizes the webpack version of angular-cli and I can successfully use ng build to compile. The output of ng build indicates that ...

Is it possible to utilize a field name with a period (".") in my data source when working with ag-grid?

I am encountering an issue with my data source, specifically with fields that have periods in their name. For example: [{ "id": 1234, "OD.name": "Andrew", "OD.age": 21 },{ "id": 1235, "OD.name": "Roofus", "OD.age": 22 }] When I try to b ...