如何使用另一个对象替换TypeScript对象中的占位符
替换TypeScript对象中的占位符
需求说明
需要将目标对象programmer中所有{xxx}格式的占位符,替换为dataToReplace对象中对应key的取值,同时支持嵌套对象的处理。
目标对象(带占位符)
const programmer = { firstname: "Phil {ReplaceMeWithValue1}", age: 21, backendDeveloper: true, skillLevels: { "JavaScript": "basic {ReplaceMeWithValue1}", "Java": "Intermediate {ReplaceMeWithValue1}"}, currentProjectName: "The Amazing App {ReplaceMeWithValue2}" };
替换值对象
const dataToReplace = { "ReplaceMeWithValue1": "ReplacingValue1", "ReplaceMeWithValue2": "ReplacingValue2" };
尝试的错误代码
ngOnInit(): void { const programmer = { firstname: "Phil {ReplaceMeWithValue1}", age: 21, backendDeveloper: true, skillLevels: { "JavaScript": "basic {ReplaceMeWithValue1}", "Java": "Intermediate {ReplaceMeWithValue1}"}, currentProjectName: "The Amazing App {ReplaceMeWithValue2}" }; const dataToReplace = { "ReplaceMeWithValue1": "ReplacingValue1", "ReplaceMeWithValue2": "ReplacingValue2" }; Object.keys(programmer).forEach(key => { this.replacePlaceHolders(programmer[key as keyof typeof programmer], dataToReplace); }); } replacePlaceHolders(value: string | number | boolean | { JavaScript: string; Java: string; }, dataToReplace: { ReplaceMeWithValue1: string; ReplaceMeWithValue2: string; }) { Object.keys(dataToReplace).forEach(key => { value = value?.replace(`{${key}}`, dataToReplace[key as keyof typeof dataToReplace]) || value; }); }
错误原因分析
- 值传递问题:
replacePlaceHolders函数参数是值传递,修改函数内的value变量不会影响原对象的属性值。 - 未处理嵌套对象:仅遍历了
programmer的顶层属性,没有递归处理skillLevels这类嵌套对象。 - 类型判断缺失:对数字、布尔值执行
replace操作会触发错误。
正确实现方案
使用递归函数遍历对象所有属性,针对不同类型做处理:
- 字符串类型:替换所有匹配的占位符
- 对象类型:递归遍历处理子属性
- 数字/布尔类型:直接保留原值
ngOnInit(): void { const programmer = { firstname: "Phil {ReplaceMeWithValue1}", age: 21, backendDeveloper: true, skillLevels: { "JavaScript": "basic {ReplaceMeWithValue1}", "Java": "Intermediate {ReplaceMeWithValue1}"}, currentProjectName: "The Amazing App {ReplaceMeWithValue2}" }; const dataToReplace = { "ReplaceMeWithValue1": "ReplacingValue1", "ReplaceMeWithValue2": "ReplacingValue2" }; this.replacePlaceholdersInObject(programmer, dataToReplace); console.log(programmer); // 输出替换后的对象 } replacePlaceholdersInObject(obj: any, replacements: Record<string, string>): void { Object.keys(obj).forEach(key => { const value = obj[key]; if (typeof value === 'string') { // 批量替换字符串中的所有占位符 Object.keys(replacements).forEach(placeholderKey => { obj[key] = value.replace(new RegExp(`{${placeholderKey}}`, 'g'), replacements[placeholderKey]); }); } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) { // 递归处理嵌套对象 this.replacePlaceholdersInObject(value, replacements); } // 数字、布尔等类型无需处理 }); }
最终效果
替换后的对象如下:
const programmer = { firstname: "Phil ReplacingValue1", age: 21, backendDeveloper: true, skillLevels: { "JavaScript": "basic ReplacingValue1", "Java": "Intermediate ReplacingValue1"}, currentProjectName: "The Amazing App ReplacingValue2" };
内容的提问来源于stack exchange,提问作者rumi
相关产品推荐
相关产品推荐

