TL;DR
如何(更好)对对象的属性进行排序?
我不是,不是,我想要的是[sort an] object property by values和它的钥匙。
问题
我有一个对象(如下所示),需要将属性(键/值对)移动到该对象的开头。
// 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
}尝试过的解决方案
当前的解决方案是删除所有其他属性并重新添加它们(将它们放在末尾)。
例如,如果我删除channel-5并重新添加它,该对象将被字符串化(通过JSON.stringify)为{"channel-1":"..." ··· "channel-9":"...","channel-5":"..."},从而有效地将该属性移到末尾。
// 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();
}发布于 2022-06-29 15:30:44
由于您有删除和添加通道的要求,根据您的条件,我已经提到了一种方法来实现您的要求,它应该适合您。
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;发布于 2022-06-29 15:09:48
复制该死的物体..。
// 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 };
}https://stackoverflow.com/questions/72803095
复制相似问题