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

如何在TypeScript中提取并格式化对象ID数组

解决方案

要得到包含拼接后id字符串的单元素数组,你可以按以下步骤实现:

  1. 从userRoles数组中提取所有id并转换为字符串类型
  2. 将提取出的id字符串用逗号拼接成一个完整字符串
  3. 将这个字符串包裹进数组中,得到目标格式

TypeScript代码示例

// 定义UserRole类型,确保类型安全
interface UserRole {
  id: number;
  name: string;
  description: string;
  checked: boolean;
  isDeleted: boolean;
  applicationId: number;
  application: string;
  totalPermissions: number;
}

// 示例数据
const userRoles: UserRole[] = [
  {
    id: 1,
    name: "Create",
    description: "This is For Create ",
    checked: false,
    isDeleted: false,
    applicationId: 1,
    application: "DMTS",
    totalPermissions: 0
  },
  {
    id: 2,
    name: "Update",
    description: "This is For Update",
    checked: false,
    isDeleted: false,
    applicationId: 1,
    application: "DMTS",
    totalPermissions: 0
  }
];

// 生成目标格式数组
const result: string[] = [userRoles.map(role => role.id.toString()).join(',')];

console.log(result); // 输出: ["1,2"]

常见误区说明

你之前的尝试可能直接执行了userRoles.map(role => role.id).join(','),这会得到一个单独的字符串"1,2",而非包含该字符串的数组。只需要将拼接后的字符串放入数组字面量中,就能得到你需要的["1,2"]格式。

内容的提问来源于stack exchange,提问作者Mohammad Samim Safi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:35:32