Reputation: 720
Here is my object
{
"1MON": "1",
"1TUE": "1",
"2TUE": "2",
"3WED": "3",
"6FRI": "6"
}
I have been trying to search hoping to get an answer but no luck.
I want to use the values to sort it
The expected output is
{
"1MON": "1",
"1TUE": "1",
"2TUE": "2",
"3WED": "3"
}
and then later on, I want to loop on it to remove the values and create a string like 1MON1TUE2TUE3WED6FRI
. The reason why i am doing this is that i want to add HTML classes like class="class-1MON1TUE2TUE3WED6FRI"
and when i want to remove 1 slot in that class i will use myClassAsString.replace(/1TUE/g, "")
please help me!
Upvotes: 0
Views: 72
Reputation: 1073
Object
keys in JavaScript aren’t sorted & you can never expect them to be. You need to convert to an Array
for that behavior.
const x = { "1MON": "2", "1TUE": "1", "2TUE": "2", "3WED": "3", "6FRI": "6" }
Object.entries(x)
.sort(([,a], [,b]) => a > b)
.map(([y]) => y)
.join("")
//=> "1MON1TUE12TUE3WED6FRI"
Upvotes: 1
Reputation: 9878
For Sorting you can try like this.
Object.keys(obj);
var obj = {"1MON":"1","1TUE":"1","2TUE":"2","3WED":"3","6FRI":"6"};
var allProperties = Object.keys(obj);
var sortedResult = allProperties.sort( (first, second) => first.localeCompare(second) );
console.log(sortedResult)
Upvotes: 0