首页 > 解决方案 > 在 JavaScript 对象中生成具有相同名称的条目

问题描述

我是 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] ] } }

标签: javascriptarraysobjectdiscord

解决方案


好的,感谢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});

推荐阅读