javascript - 在 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] ] } }
解决方案
好的,感谢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});
推荐阅读
- ios - 从Background(home)返回时iOS崩溃
- java - Appium 没有启动正确的应用程序
- unix - 删除以 – 开头的文件夹(短划线)
- visual-studio-code - 如何隐藏部分 UI?
- spring - Spring Traverson 和 OAuth2RestTemplate
- excel - 使用输入框作为密码框选择工作表 VBA EXCEL
- google-cloud-platform - 如何在 Compute Engine Google Cloud 中使用 96 个 CPU?
- swift - 在 Swiftui 中是否有一种简单的方法可以通过捏合来放大图像?
- php - 有人可以帮我将此 sql 查询转换为 laravel db 查询吗?
- julia - Julia Plotly 不显示带有子图的图