首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有更好的方法通过对象的属性对其进行排序?

是否有更好的方法通过对象的属性对其进行排序?
EN

Stack Overflow用户
提问于 2022-06-29 14:26:51
回答 2查看 40关注 0票数 -2

TL;DR

如何(更好)对对象的属性进行排序?

我不是,不是,我想要的是[sort an] object property by values和它的钥匙。

问题

我有一个对象(如下所示),需要将属性(键/值对)移动到该对象的开头。

代码语言:javascript
运行
复制
// 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":"..."},从而有效地将该属性移到末尾。

代码语言:javascript
运行
复制
// 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();
}
EN

回答 2

Stack Overflow用户

发布于 2022-06-29 15:30:44

由于您有删除和添加通道的要求,根据您的条件,我已经提到了一种方法来实现您的要求,它应该适合您。

代码语言:javascript
运行
复制
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;
票数 0
EN

Stack Overflow用户

发布于 2022-06-29 15:09:48

复制该死的物体..。

代码语言:javascript
运行
复制
// 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 };
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72803095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档