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

如何用TypeScript从对象数组生成不同键值对的新对象数组

TypeScript实现对象数组转换及动态URL生成

问题说明

现有如下输入对象数组:

const inputData = [
  {
    "description":"microsoftLocation",
    "icon":"Marker",
    "data_id":"123",
    "reference":"_1_microsoftOffice",
    "id":1,
    "text":"microsoftOffice"
  },
  {
    "description":"facebookOffice",
    "icon":"Marker",
    "data_id":"456",
    "reference":"_2_facebookOffice",
    "id":2,
    "text":"_2_microsoftOffice"
  }
];

需要转换为如下结构的数组(注:你给出的示例输出中第二个项的data_id应为456,以下按正确逻辑实现):

[
  {
    "url":"http://localhost:3000/layer?text=microsoftLocation&data_id=123",
    "text":"microsoftLocation",
    "active":true,
    "icon":"Marker"
  },
  {
    "url":"http://localhost:3000/layer?text=facebookOffice&data_id=456",
    "text":"facebookOffice",
    "active":true,
    "icon":"Marker"
  }
]

实现方案

1. 定义类型接口

为保证TypeScript类型安全,先定义输入输出的类型:

// 输入数据类型
interface InputItem {
  description: string;
  icon: string;
  data_id: string;
  reference: string;
  id: number;
  text: string;
}

// 输出数据类型
interface OutputItem {
  url: string;
  text: string;
  active: boolean;
  icon: string;
}

2. 编写转换函数

使用数组map方法遍历输入数组,提供两种动态URL生成方式:

方式一:模板字符串拼接(简单直接)

const transformData = (input: InputItem[]): OutputItem[] => {
  const baseUrl = 'http://localhost:3000/layer';
  return input.map(item => ({
    url: `${baseUrl}?text=${item.description}&data_id=${item.data_id}`,
    text: item.description,
    active: true,
    icon: item.icon
  }));
};

方式二:使用URLSearchParams(规范编码,避免特殊字符问题)

如果description或data_id包含空格、&等特殊字符,这种方式会自动编码,避免URL失效:

const transformData = (input: InputItem[]): OutputItem[] => {
  const baseUrl = new URL('http://localhost:3000/layer');
  return input.map(item => {
    const params = new URLSearchParams();
    params.append('text', item.description);
    params.append('data_id', item.data_id);
    return {
      url: `${baseUrl.origin}${baseUrl.pathname}?${params.toString()}`,
      text: item.description,
      active: true,
      icon: item.icon
    };
  });
};

3. 调用函数

const result = transformData(inputData);
console.log(result);

说明

  • 转换逻辑中,输出的text对应输入的description字段,icon直接复用输入值,active固定设为true
  • 动态URL核心是将输入的description和data_id作为查询参数拼接到底部URL后
  • 推荐使用URLSearchParams方式生成URL,可避免手动拼接时的编码问题,兼容性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:50:49