TL;DR
How can I (better) sort an object's properties?
I am not trying to [sort an] object property by values nor its keys.
Issue
I have an object (like the one below) where I need to move properties (key/value pairs) to the beginning of said object.
// Pre-sorted! But can be in any arrangement due to a hidden `channel.live` property
// name: date
{
// beginning
"channel-1": "2022-06-29T11:20:14.000Z",
"channel-2": "2022-06-29T05:58:18.000Z",
"channel-3": "2022-06-29T05:18:49.000Z",
"channel-4": "2022-06-29T04:08:35.000Z",
"channel-5": "2022-06-29T01:52:31.000Z",
"channel-6": "2022-06-29T01:00:40.000Z",
"channel-7": "2022-06-29T00:59:47.000Z",
"channel-8": "2022-06-29T00:07:28.000Z",
"channel-9": "2022-06-28T23:55:27.000Z",
// end
}
Tried Solution(s)
The current solution is to delete every other property and re-add them (putting them at the end).
E.g. If I delete channel-5
and re-add it, the object will be stringified (via JSON.stringify
) as {"channel-1":"..." ··· "channel-9":"...","channel-5":"..."}
, effectively moving the property to the end.
// Prioritize live channels!
// This will move a channel that isn't live to the end of the `Channels` object
if(!channel.live) {
delete Channels[name];
Channels[name] = date.toJSON();
}
CodePudding user response:
As you have requirement to delete and add channels as per your conditions i have mention one method to achieve your requirement it should works for you.
let Channels = {
"channel-1": "2022-06-29T11:20:14.000Z",
"channel-2": "2022-06-29T05:58:18.000Z",
"channel-3": "2022-06-29T05:18:49.000Z",
"channel-4": "2022-06-29T04:08:35.000Z",
"channel-5": "2022-06-29T01:52:31.000Z",
"channel-6": "2022-06-29T01:00:40.000Z",
"channel-7": "2022-06-29T00:59:47.000Z",
"channel-8": "2022-06-29T00:07:28.000Z",
"channel-9": "2022-06-28T23:55:27.000Z",
}
if(!channel.live) {
delete Channels[name];
Channels[name] = date.toJSON();
}
if(channel.live)
Channels = { [name]: time.toJSON(), ...Channels };
}
const updatedChannels = {};
Object.keys(Channels).sort().forEach(item => (updatedChannels[item] = Channels[item]));
Channels = updatedChannels;
CodePudding user response:
Copy the darn object...
// Prioritize live channels!
// This will move a channel that is live to the beginning of the `Channels` object
if(channel.live) {
// Ensures `...Channels` doees NOT overwrite the new property
delete Channels[name];
Channels = { [name]: time.toJSON(), ...Channels };
}