JavaScript:如何通过动态嵌套路径从多维对象取值替换占位符
解决方案
1. 实现嵌套属性读取工具函数
首先需要一个能解析带点路径、从嵌套对象中获取对应值的函数:
const getNestedProperty = (obj, path) => { // 将路径按点分割为键数组,逐层遍历对象 return path.split('.').reduce((currentObj, key) => { // 如果当前层级存在且对应键有值,继续深入;否则返回undefined return currentObj && currentObj[key] !== undefined ? currentObj[key] : undefined; }, obj); };
2. 修改占位符替换函数
替换原函数中错误的属性读取逻辑,改用上面的工具函数处理带点的路径:
const replacePlaceholdersWithData = (content) => { const replacements = {}; // 遍历占位符,构建替换映射 placeholders.forEach((placeholder) => { replacements[placeholder.find] = getNestedProperty(itemData, placeholder.column); }); // 执行占位符替换 return content.replace(/%\w+%/g, (match) => replacements[match] || match); };
3. 测试验证
调用修改后的函数,现在两个占位符都能被正确替换:
const content = "A License numbered %LICENSE% from the %APPLICANT% is received"; console.log(replacePlaceholdersWithData(content)); // 输出:'A License numbered 25/2022 from the Misir Ali Humayun is received'
补充说明
- 工具函数
getNestedProperty会自动处理路径不存在的情况,此时返回undefined,替换逻辑会保留原占位符,符合需求。 - 原代码中使用
filter遍历数组是不合适的,filter用于筛选元素,这里改用forEach更贴合语义。
内容的提问来源于stack exchange,提问作者Mayeenul Islam
相关产品推荐
相关产品推荐

