[英]Is there an better way to sort an object via its properties?
我如何(更好地)对对象的属性进行排序?
我不是试图按值或键对对象属性进行[排序] 。
我有一个对象(如下所示),我需要将属性(键/值对)移动到所述对象的开头。
// 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();
}
由于您需要根据您的条件删除和添加频道,因此我提到了一种满足您要求的方法,它应该适合您。
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;
复制该死的对象...
// 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 };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.