Home > Enterprise >  Sort array of objects according to another object
Sort array of objects according to another object

Time:11-21

I want to sort the javascript object in order of another object that have keys and sorting order

I have an object let say

sectionSorting = {
      "metrics": "12",
      "details": "3",
      "portfolio": "5"
      "backetst":"14"
}

I have another object like

sections = {
      backtest: [{key: "abc", value: "xyz"}],
      metrics: [{key: "abc", value: "xyz"}],
      details: [{key: "abc", value: "xyz"}],
      methodology: [{key: "abc", value: "xyz"}],
      portfoolio: [{key: "abc", value: "xyz"}]
}

Now I want to sort the 'sections' object in the sorting order of 'sectionSorting' object. The feilds which do not have sorting order will remail in last.

The desired Output I need is,

sortedSections = {
   details: [{key: "abc", value: "xyz"}],
   portfoolio: [{key: "abc", value: "xyz"}],
   metrics: [{key: "abc", value: "xyz"}],
   backtest: [{key: "abc", value: "xyz"}],
   methodology: [{key: "abc", value: "xyz"}],
}

I can not figure out how to do that Can Anybody help me ?

CodePudding user response:

An object is an unordered collection, so I think there is nothing call "sorting an oject keys"

CodePudding user response:

You cannot really gaurantee order of the keys in an Object. Its a map.

Option 1

Either keep a separate copy (which you already have "sectionSorting") - and use it for parsing and showing it to the user

Option 2 create an array of objects like this:

[{
        "type": "details",
        "key": "abc",
        "value": "xyz"
    },
    {
        "type": "portfolio",
        "key": "abc",
        "value": "xyz"
    }, {
        "type": "metrics",
        "key": "abc",
        "value": "xyz"
    }, {
        "type": "backtest",
        "key": "abc",
        "value": "xyz"
    }, {
        "type": "methodology",
        "key": "abc",
        "value": "xyz"
    }
]
  • Related