如何在循环中动态读取_row对象属性值并替换contentXML对应内容
解决方案
问题根因
当前代码没有将_row.title这类字符串路径解析为对象属性取值,而是直接把字符串本身作为替换值,同时dataarr中存在大量非属性路径的脏数据需要先过滤。
实现代码
let _row = {title : 'Sachin', description:'Testing Code', type: '', due_date_format: ''} // 工具函数:根据字符串路径从对象中取值 function getValueByPath(obj, path) { // 去掉前缀 _row. 后拆分路径 const realPath = path.replace(/^_row\./, '').split('.') let result = obj for(let key of realPath) { if(result && typeof result === 'object' && key in result) { result = result[key] } else { // 取不到值返回空字符串,避免替换成undefined return '' } } return result } // 过滤并提取dataarr中的有效属性路径 const validProps = dataarr.map(item => item.trim()) // 只保留 _row. 开头的合法属性项 .filter(item => /^_row\.[a-zA-Z0-9_]+/.test(item)) // 提取干净的属性路径,过滤掉附带的XML脏标签 .map(item => item.match(/^_row\.[a-zA-Z0-9_]+/)[0]) // 循环执行替换 for(let propPath of validProps) { const propValue = getValueByPath(_row, propPath) // 替换对应占位符 匹配{$_row.title}格式 contentXml = contentXml.replace(`{$${propPath}}`, propValue) }
关键逻辑说明
- 路径取值函数:把
_row.title字符串拆为属性名数组,逐层从_row对象中读取对应值,兼容后续多层嵌套属性的取值需求 - 脏数据过滤:通过正则匹配只保留
_row.开头的合法属性路径,自动剔除dataarr中的UUID、标签标记、异常XML片段等无效条目 - 异常兼容:属性不存在时默认返回空字符串,不会在XML中留下
undefined这类异常内容
内容的提问来源于stack exchange,提问作者sachin
相关产品推荐
相关产品推荐

