Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Build a Simple Dynamic Site with Node.js Creating a Basic Template Engine in Node.js A Simple Merge Utility

Marvin Müller
Marvin Müller
8,884 Points

How 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 :)

index.js
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 :)";
utilities.js
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
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Torben Korb
Front End Web Development Techdegree Graduate 89,768 Points

Hi 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
Marvin Müller
8,884 Points

Great! I didn't even get that I'm in need of an iteration here tbh. This explanation helped alot :) Thanks!