You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS中如何从JSON响应提取name字段并渲染到discord.js embed字段

实现方案

1. 解析响应提取name字段

你拿到的是JSON格式的字符串,先解析为JS数组后通过map方法遍历提取仅含name的字段即可,代码示例:

// 存储接口返回的字符串响应
const responseStr = '[{"id":"1a869e62-8993-33d0-bd54-f33753044ced","name":"Cubsonx"},{"id":"c534bcba-0096-3668-a34e-a35435e6aafb","name":"Paulina453"}]';
// 解析为JS数组
const originData = JSON.parse(responseStr);
// 提取仅含name的数组
const nameOnlyList = originData.map(item => ({ name: item.name }));
// 输出验证
console.log(nameOnlyList); // 结果符合你要求的格式

2. 渲染到discord.js Embed字段

discord.js v14及以上版本可直接用EmbedBuilder的addFields方法传入格式化后的字段数组,代码示例:

const { EmbedBuilder } = require('discord.js');

// 把提取到的name数组转为Embed要求的fields格式
const embedFields = nameOnlyList.map((item, idx) => ({
  name: `用户 ${idx + 1}`, // 字段标题可自定义
  value: item.name,
  inline: false // 设为true可让多个字段在同一行展示
}));

// 构建Embed
const nameEmbed = new EmbedBuilder()
  .setTitle('查询到的用户列表')
  .addFields(embedFields)
  .setColor('Blurple');

// 发送Embed,以 slash 命令回复为例
interaction.reply({ embeds: [nameEmbed] });

注意:Discord 规定单个Embed最多可添加25个fields,如果你的name数量超过25,需要拆分生成多个Embed或接入分页交互组件。

内容的提问来源于stack exchange,提问作者user17339117

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:15:08