Home > Software design >  Calculate min and max from json data and store the result as list
Calculate min and max from json data and store the result as list

Time:07-21

I have data in JSON format, the sample is given below. I want to calculate the min and max range for the values inside the variable i.e. align_X, align_Y, align_Z.

{"id": 0, "variable": {"align_X": 41, "align_Y": 51, "align_Z": 80}}
{"id": 1, "variable": {"align_X": 0}}
{"id": 2, "variable": {"align_Y": 1, "align_Z": 0}}

Desired output is:

        "align_X": [
            0.0,
            41.0
        ],
        "align_Y": [
            1.0,
            51.0
        ],
        "align_Z": [
            0.0,
            80.0
        ]

Any help is appropriated. Thank you

CodePudding user response:

Can you try this

var test = [{
        "id": 0,
        "variable": {
            "align_X": 41,
            "align_Y": 51,
            "align_Z": 80
        }
    }, {
        "id": 1,
        "variable": {
            "align_X": 0
        }
    }, {
        "id": 2,
        "variable": {
            "align_Y": 1,
            "align_Z": 0
        }
    }
]

var result = test.reduce((acc, cobj) => {
    for (key in cobj.variable) {
        if (acc[key]) {
            if(acc[key] > cobj.variable[key]){
                acc[key].push(parseFloat(cobj.variable[key]).toFixed(2))
            } else if (acc[key] < cobj.variable[key]){
                acc[key].push(parseFloat(cobj.variable[key]).toFixed(2))
            }
        }
        else {
            acc[key] = [];
            acc[key].push(parseFloat(cobj.variable[key]).toFixed(2))
        }
    }
    return acc;
}, []);

console.log(result);

  • Related