I have the following JSON data. How can I loop through JSON data and find possible combination based on the input of names provided?
Dimensions array:
[
{"value":"zabbixPy-API","name":"ApiName"},
{"value":"qa","name":"Stage"}
]
Example: I'm providing the following uniqueMetricsArray
which might exists in the Dimensions array
ApiId
ApiName
Stage
Example of how variable key
is constructed.
function test(name) {
if (Dimensions.name[0] && Dimensions.name[1] && Dimensions.name[2]) {
key = Dimensions.name[0].value + "_" + Dimensions.name[1].value + "_" + Dimensions.name[2].value;
} else if (Dimensions.name[0] && Dimensions.name[1]) {
key = Dimensions.name[0].value + "_" + Dimensions.name[1].value;
} else if (Dimensions.name[0]) {
key = Dimensions.name[0].value;
} else {
key = Metrics[].MetricName;
}
return key;
}
test(uniqueMetricsArray);
But in my case, the uniqueMetricsArray
lenght might be 4 or 5. So I don't want to write all possible if conditions. Is there a way I can loop through based on the input name array length and find all possible combination it might exists and construct the variable key?
So Dimensions array can be:
ApiName + Stage + ApiId
ApiName + Stage
ApiId + Stage
ApiId + ApiName
Stage
ApiId
Full Json Data:
const jsondata = {
AlarmName: "Zabbix PY 5XX - By Stage QA",
AlarmDescription: null,
AWSAccountId: "123456",
NewStateValue: "ALARM",
NewStateReason:
"Threshold Crossed: 1 out of the last 1 datapoints [1.0 (06/11/21 12:16:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for OK -> ALARM transition).",
StateChangeTime: "2021-11-06T12:17:43.811+0000",
Region: "Asia Pacific (Mumbai)",
AlarmArn: "arn:aws:cloudwatch:ap-south-1:123456: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: "",
},
};
output of console.log(uniqueMetricsArray):
ApiId
ApiName
Stage
This is how the actual if condition might look like. I just shortened it in the example above:
if (sns.Trigger.Dimensions.find(dimension => dimension.name === name[0]) && sns.Trigger.Dimensions.find(dimension => dimension.name === name[1]) && sns.Trigger.Dimensions.find(dimension => dimension.name === name[2]) ) {
var key = sns.Trigger.Dimensions.find(dimension => dimension.name === name[0]).value + '_' + sns.Trigger.Dimensions.find(dimension => dimension.name === name[1]).value + '_' + sns.Trigger.Dimensions.find(dimension => dimension.name === name[2]).value
}