Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMarvin Müller
8,884 PointsHow to implement merge method in other js file
Hey everyone,
so I'm not really getting here what the job is here. Does it want me to implement a merge method FOR that example in index.js or does it want me to write a merge method for ANY string with (%)-signs surrounding in the content?
Dont't really get how to create a placeholder here then but access a specific word (which i would store in values) inside the content string then.
Hope anyone can help :)
var utilities = require("./utilities");
var mailValues = {};
mailValues.first_name = "Janet";
var emailTemplate = "Hi %first_name%! Thanks for completing this code challenge :)";
var mergedContent = utilities.merge(emailTemplate, mailValues);
//mergedContent === "Hi Janet! Thanks for completing this code challenge :)";
function merge(content, values) {
//replace "key" in content with Values
var values = "Janet";
content = content.replace("%first_name%", values);
return content;
//content is merged content in this one
}
module.exports.merge = merge;
2 Answers
Torben Korb
Front End Web Development Techdegree Graduate 91,433 PointsHi Marvin,
the challenge works with a general merge function in which you could map the object property names to the placeholder in your string with the following logic:
- Iterate through the object properties
- Replace the object property name string with the value of the prop
- Return the transformed string
In code it looks like this for example:
function merge(content, values) {
for (let value in values) {
content = content.replace(`%${value}%`, values[value]);
}
return content;
}
There are a couple of ways to iterate through the object props, this is just one way.
Hope this helps. Happy coding!
Marvin Müller
8,884 PointsGreat! I didn't even get that I'm in need of an iteration here tbh. This explanation helped alot :) Thanks!