简体   繁体   中英

How to find particular value in JSON and display the minimum of those values in JavaScript?

I am new to JS and trying to work on a task and not find an exact solution for the same. This is the first time I am posting questions so please correct me wherever I am going wrong.

Here is my question

This is a small part of my JSON file which is more than 3000 lines for which I have given the exact format of the same JSON file

{
  "status": "success",
  "data": {
    "resultType": "vector",
    "result": [
      {
        "metric": {
          "ABC": "yes",
          "KPI": "M1",
          "__name__": "m1_status",
          "cloud": "m1",
          "cloud_kpi": "m1 status",
          "instance": "m1.e1.s1",
          "job": "m1",
          "src": "m1.m1.m1",
          "src_vm": "m1",
          "timespan": "2h"
        },
        "value": [
          1653633595.484,
          "100"
        ]
      },
      {
        "metric": {
          "ABC": "yes",
          "KPI": "M2",
          "__name__": "m1_status",
          "cloud": "m2",
          "cloud_kpi": "m1.e1",
          "instance": "m2",
          "job": "m2 services",
          "src": "m2.m3",
          "src_vm": "m2",
          "timespan": "2h"
        },
        "value": [
          1653633595.484,
          "99.919094"
        ]
      },
      {
        "metric": {
          "ABC": "yes",
          "KPI": "M2",
          "__name__": "m1_status",
          "cloud": "m2",
          "cloud_kpi": "m1.e1",
          "instance": "m2",
          "job": "m2 services",
          "src": "m2.m3",
          "src_vm": "m2",
          "timespan": "2h"
        },
        "value": [
          1653633595.484,
          "98.406375"
        ]
      },
      {
        "metric": {
          "ABC": "yes",
          "KPI": "M1",
          "__name__": "m1_status",
          "cloud": "m1",
          "cloud_kpi": "m1 status",
          "instance": "m1.e1.s1",
          "job": "m1",
          "src": "m1.m1.m1",
          "src_vm": "m1",
          "timespan": "2h"
        },
        "value": [
          1653633595.484,
          "100"
        ]
      }
}

My question is how can I check the complete JSON file and search for the cloud key and its values and display the minimum of the value.

For example I have to fetch the cloud with the name M1 in the whole JSON which may occur around 12 times.

"cloud": "m2", "cloud_kpi": "m1.e1"

in the above line, my required key will be cloud and the value will be m2. after this i have to fetch the value of this cloud that is,

"value": [ 1653633595.484, "100" ]

here the value I need is 100.

in the same way, I have to check for these values in a complete JSON file and get around 12 values

m1-100 m1-100 m2-33 m1-44 .......so on

after getting these values I need to find minimum of these and display them.

In the same way, I have to fetch all the cloud's and its minimum value that is M1-min(100,98,94...) M2-min(100,38,99,...) M3-min(100,39,20..) and so on....

I tried the map method which was confusing for me and also for each method at last I was just able to fetch all cloud names but not move further

response.json().then(function (data) {
                        var jsonarray = data["data"]["result"]                    
                        for (var k in jsonarray) {
                            if (jsonarray[k] instanceof Object) {
                                console.log(jsonarray[k].metric.cloud)                                                
                            } 
                        }
                    });

Please let me know what is the next step I have to try.

Please, check following code:

const data = response.json();
const result = data.data.result;

// mapping
const mappedArray = result.map(x => ({
    cloud: x.metric.cloud,
    value: Number(x.value[1] ?? 0)
}))
const maxSorted = mappedArray.sort((x, y) => y.value - x.value) // sorting
const minSorted = mappedArray.sort((x, y) => x.value - y.value) 
const maxValue = maxSorted[0] ?? null;
const minValue = minSorted[0] ?? null;
console.log(maxValue); // max value
console.log(minValue); // min value

Short styled:

response.json().then((data) => {
    const minValue = data.data.result.map(x => ({
        cloud: x.metric.cloud,
        value: Number(x.value[1] ?? 0)
    })).sort((x, y) => x.value - y.value)
    console.log(minValue)
})

You can use Array.filter() to find value of an array and Math.min() to find minimum value of its parameters

response.json().then(function(data){
    var jsonarray = data.data.result.filter(item => item.metric.cloud == 'm2') // here you will have all of the objects with the cloud m2
    const min = Math.min(...jsonarray.map(item => item.value[1]))
    console.log(min) // the minimum value
})
  1. filter out the objects where the cloud id matches the query.

  2. map over that array to return only the value you need.

  3. From that array find the minimum value using Math.min .

 const data={status:"success",data:{resultType:"vector",result:[{metric:{ABC:"yes",KPI:"M1",__name__:"m1_status",cloud:"m1",cloud_kpi:"m1 status",instance:"m1.e1.s1",job:"m1",src:"m1.m1.m1",src_vm:"m1",timespan:"2h"},value:[1653633595.484,"100"]},{metric:{ABC:"yes",KPI:"M2",__name__:"m1_status",cloud:"m2",cloud_kpi:"m1.e1",instance:"m2",job:"m2 services",src:"m2.m3",src_vm:"m2",timespan:"2h"},value:[1653633595.484,"99.919094"]},{metric:{ABC:"yes",KPI:"M2",__name__:"m1_status",cloud:"m2",cloud_kpi:"m1.e1",instance:"m2",job:"m2 services",src:"m2.m3",src_vm:"m2",timespan:"2h"},value:[1653633595.484,"98.406375"]},{metric:{ABC:"yes",KPI:"M1",__name__:"m1_status",cloud:"m1",cloud_kpi:"m1 status",instance:"m1.e1.s1",job:"m1",src:"m1.m1.m1",src_vm:"m1",timespan:"2h"},value:[1653633595.484,"999"]}]}}; function findMinimum(data, key) { // `filter` out the objects where the value // of `cloud` matches your query const result = data.data.result.filter(obj => { return obj.metric.cloud?.toLowerCase() === key.toLowerCase(); // For each object return the second element // of the value array }).map(obj => { return obj.value[1]; }); // `spread` out the array and use `Math.min` to // find the minimum value return Math.min(...result); } console.log(`Minimum value: ${findMinimum(data, 'M1')}`);

Additional documentation

As you want to print minimum value among all the objects that you have in the array. You can simply get all the values in a seperate array and then using Math.min(...array) you can fetch the miminum value.

Demo :

 const obj = { "status": "success", "data": { "resultType": "vector", "result": [ { "metric": { "ABC": "yes", "KPI": "M1", "__name__": "m1_status", "cloud": "m1", "cloud_kpi": "m1 status", "instance": "m1.e1.s1", "job": "m1", "src": "m1.m1.m1", "src_vm": "m1", "timespan": "2h" }, "value": [ 1653633595.484, "100" ] }, { "metric": { "ABC": "yes", "KPI": "M2", "__name__": "m1_status", "cloud": "m2", "cloud_kpi": "m1.e1", "instance": "m2", "job": "m2 services", "src": "m2.m3", "src_vm": "m2", "timespan": "2h" }, "value": [ 1653633595.484, "99.919094" ] }, { "metric": { "ABC": "yes", "KPI": "M2", "__name__": "m1_status", "cloud": "m2", "cloud_kpi": "m1.e1", "instance": "m2", "job": "m2 services", "src": "m2.m3", "src_vm": "m2", "timespan": "2h" }, "value": [ 1653633595.484, "98.406375" ] }, { "metric": { "ABC": "yes", "KPI": "M1", "__name__": "m1_status", "cloud": "m1", "cloud_kpi": "m1 status", "instance": "m1.e1.s1", "job": "m1", "src": "m1.m1.m1", "src_vm": "m1", "timespan": "2h" }, "value": [ 1653633595.484, "100" ] }] } }; const values = []; obj.data.result.forEach(obj => { obj.value.forEach(value => { values.push(Math.round(value)) }); }); console.log(Math.min(...values));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM