是否有更好的方法可以通过其属性对对象进行分类?
tl; dr
我如何(更好)分类对象的属性?
我是不是试图通过值也不是其钥匙。
问题
我有一个对象(如下面的对象),我需要将属性(键/值对)移至所述对象的开始开始。
// 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
}
尝试的解决方案
当前的解决方案是删除所有其他属性并重新添加它们(将它们放在 end End 上)。
eg 如果我删除channel-5
并重新添加它,则该对象将被串制(通过json.stringify
)为{ “ channel-1”:“ ...” em> 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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您需要根据您的条件删除和添加频道,因此我提到了一种方法来达到您的要求,它适用于您。
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.
复制该死的对象...
Copy the darn object...