我有看起来像这样的json数据
{
"students":[{"id":"001", "name":"James"},{"id":"002", "name":"Sam"}]
"courses":[{"id":"001", "name":"English"}, {"id":"002", "name":"Maths"}]
"activity_feed":[{"template":"{students:001} registered for {courses:002}"},{"template":"{students:002} dropped {courses:001}"}]
}
我想做的是使用json数据使用javascript创建活动供稿,该活动供稿将使用activity_feed中的模板字段:
詹姆斯注册了英语
山姆放弃了数学
将模板中的{students}和{courses}字段替换为学生和课程的各自名称的最佳方法是什么?
答案 0 :(得分:2)
首先,让您的数据更容易发现。例如,使您的students
和courses
索引为id
。
之后剩下的就是迭代活动模板并使用regex callback to replace the tokens
const data = {
"students":[{"id":"001", "name":"James"},{"id":"002", "name":"Sam"}],
"courses":[{"id":"001", "name":"English"}, {"id":"002", "name":"Maths"}],
"activity_feed":[{"template":"{students:001} registered for {courses:002}"},{"template":"{students:002} dropped {courses:001}"}]
}
// a simple reducer function to map "name" properties to "id" in a Map
const indexById = (map, { id, name }) => map.set(id, name)
// create an object hash of these maps
const models = {
students: data.students.reduce(indexById, new Map()),
courses: data.courses.reduce(indexById, new Map())
}
const feed = document.getElementById('feed')
data.activity_feed.forEach(({ template }) => {
let listItem = document.createElement('li')
listItem.textContent = template.replace(/\{(\w+):(\w+)\}/g,
(_, model, id) => models[model].get(id))
feed.appendChild(listItem)
})
<ul id="feed"></ul>