1

I have json data that looks like this

{
   "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}"}]
}

What I am trying to do is use the json data to create an activity feed using javascript that will make use of the template field in activity_feed:

James registered for English

Sam dropped Mathematics

What is the best way to substitute the {students} and {courses} field in template with the respective names of the students and the courses?

4
  • 1
    What already you try so far? SO is help people to solve the problem not ask for free code Commented Mar 13, 2019 at 4:04
  • Honestly I am kinda new at this, if this was python, I would have used regex. I am looking for a way to extract the fields from the template Commented Mar 13, 2019 at 4:06
  • what you need is create looping based on your activity_feed. and why template format not like James registered for English? why using {students:001} ? Commented Mar 13, 2019 at 4:09
  • the assignment format looks like that Commented Mar 13, 2019 at 4:24

1 Answer 1

2

I'd start by making your data easier to discover. For example, make your students and courses indexed by id.

All that's left after that is to iterate your activity templates and use a 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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.