如何在JavaScript中高效实现含模板变量的JSON数组插值(无第三方包)
需求说明
给定包含模板变量的JSON数组template和存储实际数据的JSON对象replacers,需在不使用第三方包的前提下完成以下操作:
- 将
template中的模板变量(格式为${xxx.xxx})替换为replacers中对应的实际值 - 为
template的每个数组元素添加对应的title字段(如student1对应"Student 1")
最终得到目标JSON数组。
原始代码示例
const template = [ { records: [ { key: "Roll No", value: "${student1.rollNo}" }, { key: "Class", value: "${student1.class} standard" }, ], }, { records: [ { key: "Roll No", value: "${student2.rollNo}" }, { key: "Class", value: "${student2.class} standard" }, ] } ]; const replacers = { student1: { rollNo: 100, class: 10 }, student2: { rollNo: 101, class: 12 } };
替换后中间结果
const intermediateResult = [ { records: [ { key: "Roll No", value: "100" }, { key: "Class", value: "10 standard" } ], }, { records: [ { key: "Roll No", value: "101" }, { key: "Class", value: "12 standard" } ] } ];
最终目标结果
const finalResult = [ { title: "Student 1", records: [ { key: "Roll No", value: "100" }, { key: "Class", value: "10 standard" } ], }, { title: "Student 2", records: [ { key: "Roll No", value: "101" }, { key: "Class", value: "12 standard" } ] } ];
实现方案
以下是纯原生JavaScript的实现代码,无需依赖任何第三方库:
// 原始数据 const template = [ { records: [ { key: "Roll No", value: "${student1.rollNo}" }, { key: "Class", value: "${student1.class} standard" }, ], }, { records: [ { key: "Roll No", value: "${student2.rollNo}" }, { key: "Class", value: "${student2.class} standard" }, ] } ]; const replacers = { student1: { rollNo: 100, class: 10 }, student2: { rollNo: 101, class: 12 } }; // 处理模板的函数 function processTemplate(template, replacers) { // 获取replacers中的学生键名,与template元素一一对应 const studentKeys = Object.keys(replacers); return template.map((item, index) => { const studentKey = studentKeys[index]; // 生成对应的title const title = `Student ${studentKey.slice(-1)}`; // 替换每条record中的模板变量 const processedRecords = item.records.map(record => { // 匹配${xxx.xxx}格式的模板变量 const replacedValue = record.value.replace(/\${([^}]+)}/g, (match, path) => { // 将路径拆分为层级,如"student1.rollNo"拆分为["student1", "rollNo"] const pathSegments = path.split('.'); let currentValue = replacers; // 逐层遍历路径获取对应值 for (const segment of pathSegments) { currentValue = currentValue[segment]; // 如果路径不存在,保留原模板变量 if (currentValue === undefined) break; } return currentValue !== undefined ? String(currentValue) : match; }); return { ...record, value: replacedValue }; }); return { title, records: processedRecords }; }); } // 执行处理并打印结果 const result = processTemplate(template, replacers); console.log(JSON.stringify(result, null, 2));
代码说明
- 键名匹配:通过
Object.keys(replacers)获取所有学生键名,保证与template数组的元素顺序对应 - title生成:从学生键名(如
student1)中提取数字部分,拼接成"Student 1"格式的标题 - 模板变量替换:使用正则表达式匹配
${xxx.xxx}格式的变量,拆分路径后从replacers中逐层查找对应值,替换到原字符串中;若路径不存在则保留原变量 - 不可变处理:使用扩展运算符(
...)复制原对象,避免修改原始数据
内容的提问来源于stack exchange,提问作者Giri M
相关产品推荐
相关产品推荐

