简体   繁体   中英

JSON - manipulating elements

So I have JSON that looks like -

[
 {
  "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
  "Pivot1": 40.00000,
  "Pivot2": 38.00000,
  "Pivot3": 18.00000,
  "Total": 96.00000,
  "Average": 32.00000,
  "IsTotal": 0,
  "MetricOrder": 1
 }
]

using javascript and/or jQuery I'd like to end up with -

[
 {
  "Metric":"7e70661f-e266-4745-9b1b-c5c5691e9746",
  "Pivot1":40.00000,
  "Pivot1DFA": 125.000%,
  "Pivot2":38.00000,
  "Pivot2DFA": 118.750%,
  "Pivot3":18.00000,
  "Pivot3DFA": 56.250%,
  "Total":96.00000,
  "Average":32.00000,
  "IsTotal":0,
  "MetricOrder":1
 }
]

(DFA represents Difference from Average).

In this example I have 3 Pivot columns. I could and probably will have more, but I don't know that until I get the JSON back from the server.

How do I accomplish this?

Pure javascript solution
For all keys in json that starts with "Pivot", add one more key in result json with the desired operation

json = {"Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
        "Pivot1": 40.00000,
        "Pivot2": 38.00000,
        "Pivot3": 18.00000,
        "Total": 96.00000,
        "Average": 32.00000,
        "IsTotal": 0,
        "MetricOrder": 1
}
json_parsed = {}
Object.keys(json).forEach(
    function(e){ 
        json_parsed[e] = json[e]
        if(e.indexOf("Pivot") === 0){
            var avg = json["Average"]
            json_parsed[e+"DFA"] = ((json[e] / avg ) * 100.0) +"%"
        }
    }
)

With this solution json_parsed has the same order than json var and you can control keys order

>>>> Object.keys(json_parsed)
>>>> ["Metric", "Pivot1", "Pivot1DFA", "Pivot2", "Pivot2DFA", "Pivot3", "Pivot3DFA", "Total", "Average", "IsTotal", "MetricOrder"]

jQuery has a .each() function that would be useful here.

it looks like you'd have to make two passes, one to calculate the average, and another to calculate the DFA

var values = [{"Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
               "Pivot1": 40.00000,
               "Pivot2": 38.00000,
               "Pivot3": 18.00000,
               "Total": 96.00000,
               "Average": 32.00000,
               "IsTotal": 0,
               "MetricOrder": 1
              }];

var totals = {};
var count = values.length;
$.each(values, function(idx, obj){
    $.each(obj, function(idx2, val){
        if(idx2.indexOf('Pivot') == 0){
            if(typeof totals[idx2] == 'undefined'){
                totals[idx2] = 0.0;
            }
            totals[idx2] += obj[idx2];
        }
    });
});
$.each(values, function(idx, obj){
    $.each(obj, function(idx2, val){
        if(idx2.indexOf('Pivot') == 0){
            obj[idx2+'DFA'] = totals[idx2] / obj[idx2];
        }
    });
});
console.log(values);

and then whatever method you want to calculate percent, multiply by 100 and make it a string with the % symbol is up to you but can be done in the second loop.

I haven't done the actual calcuation logic, just provided a default value, you could put up your calculation logic. The final object "jsonData" after all process, will give you the desired output.

        var jsonData = [
                        {
                            "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
                            "Pivot1": 40,
                            "Pivot2": 38,
                            "Pivot3": 18,
                            "Total": 96,
                            "Average": 32,
                            "IsTotal": 0,
                            "MetricOrder": 1
                        }
                    ];
        var properties = [];
        for (var o in jsonData[0]) {
            if (o.indexOf('Pivot') > -1)
                properties.push(o);
        }
        $.each(jsonData, function (index, value) {
            $.each(properties, function (idx, val) {
                var currentValue = value[val];
                value[val + 'DFA'] = "0"; //your calculation logic to be done here
            });
        });

Hope this helps :)

first convert json to an object:

myJsonObj = JSON.parse(myJsonStr);

second manipulate object:

myJsonObj['Pivot1DFA'] = 125.000%;

etc.

third convert back to json:

myJsonStr = JSON.stringify(myJsonObj);

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