Home > Software design >  Nodejs get the length of a array without using JQ
Nodejs get the length of a array without using JQ

Time:11-06

How to get the length of Dimensions array in nodejs? It can possible have 2 blocks or sometimes just 1. I want to write a if condition based on the length. This is inside AWS-Lambda function so I can't use JQ there (I'm not sure if I could).

Example: I want to put these variables inside a if condition based on the length

var sns_DimensionsValue_ApiName = sns.Trigger.Dimensions[0].value;

var sns_DimensionsValue_StageName = sns.Trigger.Dimensions[1].value;

Output of Dimensions array:

        "Dimensions": [
            {
                "value": "zabbixPy-API",
                "name": "ApiName"
            },
            {
                "value": "qa",
                "name": "Stage"
            }
        ],

In some cases the dimension will have only one item. In this example we have 2 (ApiName and Stage name). It depends on the cloudwatch metric type.

Full output Code:

{
    "AlarmName": "Zabbix PY 5XX - By Stage QA",
    "AlarmDescription": null,
    "AWSAccountId": "123456789",
    "NewStateValue": "ALARM",
    "NewStateReason": "Threshold Crossed: 1 out of the last 1 datapoints [1.0 (05/11/21 09:54:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for OK -> ALARM transition).",
    "StateChangeTime": "2021-11-05T09:55:43.823 0000",
    "Region": "Asia Pacific (Mumbai)",
    "AlarmArn": "arn:aws:cloudwatch:ap-south-1:123456789:alarm:Zabbix PY 5XX - By Stage QA",
    "OldStateValue": "INSUFFICIENT_DATA",
    "Trigger": {
        "MetricName": "5XXError",
        "Namespace": "AWS/ApiGateway",
        "StatisticType": "Statistic",
        "Statistic": "MINIMUM",
        "Unit": null,
        "Dimensions": [
            {
                "value": "zabbixPy-API",
                "name": "ApiName"
            },
            {
                "value": "qa",
                "name": "Stage"
            }
        ],
        "Period": 60,
        "EvaluationPeriods": 1,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "Threshold": 1,
        "TreatMissingData": "- TreatMissingData:                    missing",
        "EvaluateLowSampleCountPercentile": ""
    }
}

CodePudding user response:

Native JS arrays have a .length property that you can use for your need.

CodePudding user response:

Works with regular javascript.

var dimLength = sns.Trigger.Dimensions.length;
if(dimLength === 1){
   var sns_DimensionsValue_ApiName = sns.Trigger.Dimensions[0].value;
} else if(dimLength === 2){
   var sns_DimensionsValue_StageName = sns.Trigger.Dimensions[1].value;
}
  • Related