0

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 ?

Srushti Shah
  • 810
  • 3
  • 17
  • Why sort an object? you access values of object by keys. – Ping Nov 21 '22 at 04:40
  • I want to show values of object in order that user decides – Srushti Shah Nov 21 '22 at 04:45
  • [using property order for fundamental program logic probably isn't a good idea](https://stackoverflow.com/a/5525820/17447) – naveen Nov 21 '22 at 04:46
  • You cannot really gaurantee order of the keys in an Object. Its a map. Either keep a separate copy (which you already have "sectionSorting") - and use it for parsing OR create an array of objects – avin Nov 21 '22 at 04:47
  • @SrushtiShah object in JavaScript is not designed for this, if you want things to be shown in order, use an array to setup the order, and output results by a for...of loop of that say array to access the object values. – Ping Nov 21 '22 at 04:49

2 Answers2

0

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

WestMountain
  • 136
  • 1
  • 1
  • 8
0

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"
    }
]
avin
  • 459
  • 5
  • 14