1

I want to sort the below json response based on an array.

{
    "expanded": {
        "developer": {
            "numFound": 1,
            "start": 0,
            "maxScore": 0.13050619,
            "docs": [
                {
                    "title": "developer"
                }
            ]
        },
        "shop": {
            "numFound": 1,
            "start": 0,
            "maxScore": 1.1272022,
            "docs": [
                {
                    "title": "shop"
                }
            ]
        },
        "support": {
            "numFound": 84,
            "start": 0,
            "maxScore": 1.3669837,
            "docs": [
                {
                    "title": "support"
                }
            ]
        }
    }
}

I want to sort based on the below sort array (in same order as below).

[ 'shop', 'support', 'developer']

Is there a way to sort this json based on some custom value?

1
  • Filter them to an array, then sorting? Commented Feb 28, 2017 at 23:45

2 Answers 2

3

You can't sort json, but you can create an array of objects and sort that:

let foo = {"expanded": {"developer": {"numFound": 1,"start": 0,"maxScore": 0.13050619,"docs": [{"title": "developer"}]},"shop": {"numFound": 1,"start": 0,"maxScore": 1.1272022,"docs": [{"title": "shop"}]},"support": {"numFound": 84,"start": 0,"maxScore": 1.3669837,"docs": [{"title": "support"}]}}};

let orderArr = ['shop', 'support', 'developer'];

let res = Object.keys(foo.expanded)
    .map(a => ({[a] : foo.expanded[a]}))
    .sort((a,b) => (orderArr.indexOf(Object.keys(a)[0]) + 1) - (orderArr.indexOf(Object.keys(b)[0]) + 1));

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

2

It seems that there is no need to sort since the order for the properties is explicitly defined. Instead, just place the required objects into an array:

let ordered = ['shop', 'support', 'developer'].map(property => {
  return {[property]: foo.expanded[property]};
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.