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

TypeScript如何替换数组对象内的字符串占位符为post请求返回的参数值

实现思路

直接遍历noteParams的键值对,批量替换row2属性中对应的占位符即可,你可以选择生成新数组不修改原数据,也可以直接修改原数组。

实现代码

// 原存储数组
export const noteArr = [
  {row1: "test1", row2: "Theme: rowTheme \n" + "/row/details?id=rowId"},
];
// 接口获取的参数
const noteParams = { rowTheme: "asd", rowId: "3768" };

// 方案1:生成新数组(不修改原数组)
const processedArr = noteArr.map(item => {
  let newRow2 = item.row2;
  Object.keys(noteParams).forEach(key => {
    // 替换所有匹配的占位符
    newRow2 = newRow2.replaceAll(key, noteParams[key]);
  })
  return { ...item, row2: newRow2 };
})

// 方案2:直接修改原数组
// noteArr.forEach(item => {
//   Object.keys(noteParams).forEach(key => {
//     item.row2 = item.row2.replaceAll(key, noteParams[key]);
//   })
// })

console.log(processedArr[0])
// 输出结果:{row1: "test1", row2: "Theme: asd \n/row/details?id=3768"}

优化建议

如果怕占位符和row2里的其他普通字符串冲突,可以给占位符加特殊标识避免误替换,比如把占位符写成{{rowTheme}}、{{rowId}}的格式,替换时修改对应匹配规则即可:

// 替换逻辑调整为
newRow2 = newRow2.replaceAll(`{{${key}}}`, noteParams[key]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:54:03