🎉

TypeScriptでオブジェクトのプレースホルダを置換する

に公開
function replaceKeywords(obj: any, replacements: Record<string, string>): any {
  if (typeof obj === 'string') {
    let result = obj;
    for (const [key, value] of Object.entries(replacements)) {
      result = result.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    }
    return result;
  } else if (Array.isArray(obj)) {
    return obj.map(item => replaceKeywords(item, replacements));
  } else if (obj && typeof obj === 'object') {
    const result: any = {};
    for (const key in obj) {
      result[key] = replaceKeywords(obj[key], replacements);
    }
    return result;
  }
  return obj;
}

Discussion