【问题标题】:Generating Entries with Same Name in JavaScript Object在 JavaScript 对象中生成具有相同名称的条目
【发布时间】:2019-12-02 02:16:21
【问题描述】:

我是 Javascript 新手,我做了一些研究,但我似乎无法弄清楚如何生成多个具有相同名称键但不同值的列表。我正在尝试为应该如下所示的嵌入消息生成代码:

{embed: {
    color: 3447003,
    title: "title",
    description: "desc",
    fields: [{
        name: "header 1",
        value: "text 1"
      },
      {
        name: "header 2",
        value: "text 2"
      },
      {
        name: "header 3",
        value: "text 3"
      }
    ]
  }
}

这是为了在嵌入中自动生成我的命令列表,因此我不必继续返回并编辑它。

我主要是尝试使用“名称”和“值”条目获取多个“字段”,并尝试在一行中为“值”添加所有命令。

这是我的代码:

let currentCategory = "";
    var embed = {
      "title": "= __Command List__ =",
      "description": `[Use ${message.settings.prefix}help <commandname> for details]`,
      "color": 2563607,
      fields : []
    };
    const sorted = myCommands.array().sort((p, c) => p.help.category > c.help.category ? 1 :  p.help.name > c.help.name && p.help.category === c.help.category ? 1 : -1 );
    sorted.forEach( c => {
      const cat = c.help.category.toProperCase();
      if (currentCategory !== cat) {
        embed.fields = [{name : `${cat}`,value : ""}];
        currentCategory = cat;
      }
      embed.fields[0].value += ` \`${c.help.name}\``;
    });
    console.log({embed});
    message.channel.send({embed});

我使用console.log({embed}); 打印它在控制台中生成的代码,这就是显示的内容。

{ embed:
   { title: '= __Command List__ =',
     description: '[Use y!help <commandname> for details]',
     color: 2563607,
     fields: [ [Object] ] } }

【问题讨论】:

标签: javascript arrays object discord


【解决方案1】:

好的,感谢PM 77-1

对于任何想知道的人,我基本上设置和索引 -1 并使其添加到索引中,同时为每个新类别循环。

let currentCategory = "";
    let index = -1;
    var embed = {
      "title": "= __Command List__ =",
      "description": `[Use ${message.settings.prefix}help <commandname> for details]`,
      "color": 2563607,
      fields : []
    };
    const sorted = myCommands.array().sort((p, c) => p.help.category > c.help.category ? 1 :  p.help.name > c.help.name && p.help.category === c.help.category ? 1 : -1 );
    sorted.forEach( c => {
      const cat = c.help.category.toProperCase();
      if (currentCategory !== cat) {
        index = index + 1
        embed.fields[index] = {name : `${cat}`,value : ""};
        currentCategory = cat;
      }
      embed.fields[index].value += ` \`${c.help.name}\``;
    });
    console.log({embed});
    message.channel.send({embed});

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 2013-06-16
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多