JavaScript中如何识别对象占位符、调用API并替换数据?
问题描述
原对象
{ "object": { "id": 1, "string": { "stringWithoutData": "there is no data here", "stringWithData": "this is a string with this {{data.extended.action}}" } } }
API返回结果
{ "data": { "extended": { "action": "new sub string value" } } }
期望修改后的对象
{ "object": { "id": 1, "string": { "stringWithoutData": "there is no data here", "stringWithData": "this is a string with this new sub string value" } } }
核心需求
遍历嵌套对象,识别所有以{{开头、}}结尾的占位符,提取占位符内的路径(如data.extended.action),从API返回数据中取出对应路径的值,替换原对象中的占位符。此前尝试遍历对象,但无法正确提取占位符及完成替换。
解决方案
以下以JavaScript为例,实现完整的替换逻辑:
完整代码示例
// 原对象 const originalObj = { "object": { "id": 1, "string": { "stringWithoutData": "there is no data here", "stringWithData": "this is a string with this {{data.extended.action}}" } } }; // API返回的数据 const apiResponse = { "data": { "extended": { "action": "new sub string value" } } }; // 根据路径从对象中取值的函数 function getNestedValue(obj, path) { return path.split('.').reduce((current, key) => { return current?.[key] ?? ''; // 路径不存在时返回空字符串避免报错 }, obj); } // 递归遍历并替换占位符的函数 function replacePlaceholders(obj, dataSource) { // 处理数组(如果存在嵌套数组场景) if (Array.isArray(obj)) { return obj.map(item => replacePlaceholders(item, dataSource)); } // 处理嵌套对象 if (typeof obj === 'object' && obj !== null) { const newObj = {}; for (const key in obj) { newObj[key] = replacePlaceholders(obj[key], dataSource); } return newObj; } // 处理字符串类型,检查并替换占位符 if (typeof obj === 'string') { // 全局匹配所有{{...}}格式的占位符,非贪婪模式避免匹配跨占位符内容 const placeholderRegex = /{{(.*?)}}/g; return obj.replace(placeholderRegex, (match, path) => { // 去除路径前后的空格,兼容用户输入时的格式误差 const cleanPath = path.trim(); return getNestedValue(dataSource, cleanPath); }); } // 非字符串/对象/数组类型直接返回原值 return obj; } // 执行替换并输出结果 const result = replacePlaceholders(originalObj, apiResponse); console.log(JSON.stringify(result, null, 2));
关键逻辑说明
- 递归遍历:
replacePlaceholders函数会逐层处理数组、对象和基本类型,确保所有嵌套层级的字符串都被检查。 - 路径取值:
getNestedValue用reduce方法逐层解析.分隔的路径,实现嵌套属性的安全访问。 - 正则匹配:使用
/{{(.*?)}}/g全局匹配占位符,.*?的非贪婪模式确保只匹配单个占位符内容,避免跨占位符错误匹配。 - 容错处理:路径不存在时返回空字符串,防止因API数据结构变化导致的报错。
内容的提问来源于stack exchange,提问作者Vikram
相关产品推荐
相关产品推荐

