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.