I have an object
{
"undefined": 10,
"women": 5,
"men": 3,
}
And I need to sort it, so it looks like
{
"men": 3,
"women": 5,
"undefined": 10,
}
How can I do it?
I have tried to sort it like that, but it works alphabetically.
const object = {
"undefined": 10,
"women": 3,
"men": 6
}
const entries = Object.entries(object).sort();
const sortedObject = Object.fromEntries(entries);
console.log(sortedObject);
/*
Expected result:
{
"men": 6,
"women": 3,
"undefined": 10
}
*/
This is what I am trying to do:
statsParser.js
import { t } from "i18n";
export default (genders) => {
if (!genders) return;
const entries = Object.entries(genders).sort(([, a], [, b]) => b - a); // What if I want to order the map so it looks like { men: x, women: y, undefined: z } instead of by value in desc order?
const translatedEntries = entries.map((entry) => [
t(`content.stats.genders.${entry[0].toLowerCase()}`),
entry[1],
]);
const translatedGenders = Object.fromEntries(translatedEntries);
return translatedGenders;
};
To sort json object using key is easy as below:
const unordered = {
"undefined": 10,
"women": 5,
"men": 3,
}
const ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log(JSON.stringify(ordered));
To sort json object using value, you need convert your object into array using Object.entries. Then you sort that array using value and prepare string using map function and finally parse it into json.
const unordered = {
"undefined": 10,
"women": 5,
"men": 3,
}
const arrOfArrays = Object.entries(unordered);
const ordered = arrOfArrays.sort((a, b) => {
const aVal = Object.values(a)[1];
const bVal = Object.values(b)[1];
return aVal - bVal;
});
var jsonString = "{";
ordered.map(obj => {
var json = { ...obj };
jsonString += `"${json[0]}":"${json[1]}",`;
});
jsonString = jsonString.replace(/,\s*$/, "");
jsonString += "}";
console.log(JSON.parse(jsonString));