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.

4
  • 2
    Why do you want or need to do this? The order of object properties is generally irrelevant Commented Mar 2, 2022 at 23:46
  • 2
    If you want to set and maintain a certain order of elements, use an array instead of an object. Commented Mar 2, 2022 at 23:49
  • FYI Object.fromEntries() is a shorter alternative to your reduce() Commented Mar 2, 2022 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)) Commented Mar 3, 2022 at 0:10

0

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.