Question

This is my JSON structure :

Root
|- cells []
     |-Individual cells containing the following
                         |- Facts (Object)
                         |- Measures (Object)
                                 |- Key values pairs
|- other values

I need to sort the values in the measures object in-place. Will it be possible? If not, what should be the optimized way to approach this? I could have those values extracted into a temporary array and then sort them, and then search for their respective keys and re-order the entire JSON. But that doesn't seem an optimized solution.

I'm basically trying to achieve sorting in the jsHypercube : https://github.com/thesmart/js-hypercube . Searched the library, but couldn't find any sort method.


Adding a snap of sample JSON : enter image description here

Expected output is a sorted array of _cells based on any key in the measures object, like Cost, Profit or Revenue.


As per the comments of @FelixKling , I believe the data should be sorted before serializing it into a JavaScript Object. The original data before serialization : enter image description here

Was it helpful?

Solution

With help of @FelixKling's suggestion, I was able to sort it using a simple block of code. Posting it since it might be helpful for someone else.

tempCube.sort(function(a, b) {
        var valueA, valueB;        

        valueA = a.measures.Cost; 
        valueB = b.measures.Cost;
        if (valueA < valueB) {
            return -1;
        }
        else if (valueA > valueB) {
            return 1;
        }
        return 0;
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top