0

I have an object whose keys are dynamically generated by the data receoved from the api response.

code:

var object = {
ABS-Test: 11,
CAS-tab-Running: 9,
ABS-tag-objetc: 9,
Internet-Facing-ABS: 9,
ABS-connector-test: 11
}

How can I sort using the object above based on value and key. Example of the expected output when sorted based on key of the object;

var sortedObject = {
    ABS-connector-test: 11,
    ABS-tag-objetc: 9,
    ABS-Test: 11,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9
    }


var sortedValueObject = {
    ABS-tag-objetc: 9,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9,
    ABS-connector-test: 11,
    ABS-Test: 11,
    }

I have referred Sort a JavaScript object by key or value; ES6 and SO far I have this for sorting by value:

sorted_object = Object.entries(unsorted_object)
  .sort(([,v1], [,v2]) => +v2 - +v1)
  .reduce((r, [k, v]) => Object.assign(r, { [k]: v }), {});

and this for sorting by key:

sorted_object = Object.entries(data)
  .sort((a, b) => a[1] - b[1])
  .reduce((a, [key, val]) => {
    a[key] = val;
    return a;
  }, {});

Both of them return output in certain order (either ascendeing or desc). Do we have a logic or a lodash method that'll help to toggle the sorting logic based on the asc or desc value provided?

I tried via the _orderBy() and _sortBy() from lodash Reactjs, however they require a static key value to be passed to get the results.

user1234
  • 3,000
  • 4
  • 50
  • 102
  • 2
    Why do you want or need to do this? The order of object properties is generally irrelevant – Phil Mar 02 '22 at 23:46
  • 2
    If you want to set and maintain a certain order of elements, use an array instead of an object. – Kinglish Mar 02 '22 at 23:49
  • FYI [Object.fromEntries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) is a shorter alternative to your `reduce()` – Phil Mar 02 '22 at 23:51
  • Not sure I understand your question right, but to toggle asc/desc I'd say that all you need is to switch the elements in the `sort()` method based on the '_mode_' you pass to it: `sort((a, b) => 'ASC' ? (a-b) : (b-a))` – cheesyMan Mar 03 '22 at 00:10

0 Answers0