cbll
cbll

Reputation: 7219

Sorting JSON objects by string value to Javascript array

I have a React.js application that is being fed JSON data from the backend.

I'm unsure of how to sort the objects by a key that is a string rather than number - if it was the latter, I could've used numerous examples.

Here's a sample string. The object I want to sort for is High, Medium and Low. I want to sort with high first, then medium, and then low ones.

{"Medium":{"This is inbetween!":[{"key":"123", "type":"inbetween"}]},
"High":{"This is the highest!":[{"key":"3333", "type":"highest"}]},
"Medium":{"This is inbetween again":[{"key":"12333123", "type":"power"}]},
"Low":{"This is the lowest!":[{"key":"123465", "type":"super low"}]}}

How do I sort this JSON data into strings high, medium and low in an array?

Upvotes: 0

Views: 1888

Answers (1)

baao
baao

Reputation: 73241

So as your "object" is most probably an array (it would be an invalid object, with duplicate declarations, e.g. of the Medium property) I assume that the following will be how your data is...

You can sort that array of objects by creating another "order" object, assigning an order number to the keys.

I think the following snippet will do what you want:

let arr = [
    {
        "Medium": {
            "This is inbetween!": [
                {
                    "key": "123",
                    "type": "inbetween"
                }
            ]
        }
    },
    {
        "High": {
            "This is the highest!": [
                {
                    "key": "3333",
                    "type": "highest"
                }
            ]
        }
    },
    {
        "Medium": {
            "This is inbetween again": [
                {
                    "key": "12333123",
                    "type": "power"
                }
            ]
        }
    },
    {
        "Low": {
            "This is the lowest!": [
                {
                    "key": "123465",
                    "type": "super low"
                }
            ]
        }
    }
];

let order = {
    High: -3,
    Medium: -2,
    Low: -1
}


arr = arr.sort((a,b) => {
    return order[Object.keys(a)[0]] - order[Object.keys(b)[0]];
});

console.log(arr);

Upvotes: 2

Related Questions